2

I want to run mybat.bat file located in MyFolder which is different from the current directory. I used the following code:

subprocess.Popen(["mybat", MyArg],
                  cwd=MyFolder,
                  stdout=subprocess.PIPE,
                  stderr=subprocess.PIPE,
                  stdin=subprocess.PIPE)

However, I get the following error:

"WindowsError: [Error 2] The system cannot find the file specified"

I should mention that if I replace mybat with another program in the PATH such as notepad it works absolutely fine.

1
  • Yes. I do have mybat.bat file in MyFolder. Commented Sep 2, 2015 at 16:53

2 Answers 2

2

The working directory is changed only in the child process i.e., cwd=MyFolder does not make os.path.join(MyFolder, "mybat.bat") available. Try:

p = Popen([os.path.join(MyFolder, "mybat.bat"), MyArg], cwd=MyFolder)

You could use %~dp0 inside your bat-file, to get the directory where the bat-file resides instead of cwd=MyFolder as @eryksun suggested.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Sebastian. Your solution solved the problem too.
A properly written batch file shouldn't in general require setting cwd to find files relative to itself. It should use %~dp0 to get the fully-qualified path of the batch file, i.e. the [d]rive and [p]ath of the .bat file (command-line argument 0).
0

adding shell=True to command solved the problem.

1 Comment

you could avoid shell=True if you provide the explicit .bat extension and the complete path to the bat-file if the error persists. See this answer on the difference between how the search for an executable differs in shell=False|True cases. Look at Windows questions in the subprocess tag info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy 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.