0

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 inC:\users\me\desktop\python while the batch file is in a folderC:\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. theC:\users\me part might be different).

This is the script I tried (executed from the "python" folder on desktop)

from subprocess import callpath = "..\batch"call([path+"\test.bat"])

Result: file not found

askedFeb 17, 2017 at 10:06
vdvaxel's user avatar
3

2 Answers2

1

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]: testOut[2]: '..\x08foo'

Use raw strings instead:

In [3]: test = r"..\bfoo"In [4]: testOut[4]: '..\\bfoo'

And actually, the best way to combine path segments in python is by usingos.path.join. This will automatically take care of the backslash vs. slash issues for Unix-lie vs. Windows operating systems.

answeredFeb 17, 2017 at 10:13
languitar's user avatar
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks, that worked. However, when I run the Python script, it now shows me the code inside the batch file without actually executing it?
On the command line? Or does it open a new window. However, this is probably actually a different question.
Yes it shows the code on the command line and doesn't open a new window.
When I put the Python script in the same folder as the batch file, it works. But for some reason it doesn't work from a different folder.
Have a look at the marked duplicate questionstackoverflow.com/questions/1818774/…. Maybe it solves the issue?
|
0

Useos.path,

import os dir_path = os.path.dirname(os.path.realpath(__file__))  # get the full path of the Python fileparent_dir = os.path.dirname(dir_path)new_path = os.path.join(parent_dir, 'bath', 'test.bat')
answeredFeb 17, 2017 at 10:18
SparkAndShine's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.