Skip to content Skip to sidebar Skip to footer

Running A File In The Same Directory As The Invoking Python Module Or Script

How can I run a batch file with Python (in the same directory as the Python scripts)? Note that the directory cannot be constant as it can be changed from one user to another.

Solution 1:

You need to find out where your script is and assemble an absolute path:

import os
import subprocess

dirname = os.path.dirname(os.path.abspath(__file__))
cmd = os.path.join(dirname, 'mybatch_file')

subprocess.call(cmd)

In Steps

You can find out the name of script with:

__file__

Now make it an absolute path:

os.path.abspath

and get the directory it is in:

os.path.dirname

Finally, join this path with your batch file name:

os.path.join

before you feed it to:

subprocess.call

Solution 2:

you can achieve it use subprocess module

from subprocess import call
comando ='path_to_the_script'call(comando, shell=True)

Post a Comment for "Running A File In The Same Directory As The Invoking Python Module Or Script"