I'm trying to execute a batch file using a Python script. Is this possible? The Python script is in a different folder than the batch file. For example, the Python script is in C:\users\me\desktop\python while the batch file is in a folder C:\users\me\desktop\batch. I prefer not to use the full path to the batch file because I want it to work on other people's computer as well (i.e. the C:\users\me part might be different).
This is the script I tried (executed from the "python" folder on desktop)
from subprocess import call
path = "..\batch"
call([path+"\test.bat"])
Result: file not found
-
Possible duplicate of (stackoverflow.com/questions/5469301/…)Chanda Korat– Chanda Korat2017年02月17日 10:11:28 +00:00Commented Feb 17, 2017 at 10:11
-
2Possible duplicate of Run a .bat file using python codeFlorian Koch– Florian Koch2017年02月17日 10:13:32 +00:00Commented Feb 17, 2017 at 10:13
-
Possible duplicate of Executing a subprocess failsfeedMe– feedMe2017年02月17日 10:45:20 +00:00Commented Feb 17, 2017 at 10:45
2 Answers 2
Backslash escapes special characters in python. Therefore, the paths that you are creating here are not the ones you think they are:
In [1]: test = "..\bfoo"
In [2]: test
Out[2]: '..\x08foo'
Use raw strings instead:
In [3]: test = r"..\bfoo"
In [4]: test
Out[4]: '..\\bfoo'
And actually, the best way to combine path segments in python is by using os.path.join. This will automatically take care of the backslash vs. slash issues for Unix-lie vs. Windows operating systems.
9 Comments
Use os.path,
import os
dir_path = os.path.dirname(os.path.realpath(__file__)) # get the full path of the Python file
parent_dir = os.path.dirname(dir_path)
new_path = os.path.join(parent_dir, 'bath', 'test.bat')