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.

greole
  • 3,766
  • 5
  • 24
  • 48
MZX
  • 33
  • 3

2 Answers2

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.

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518
  • Thanks Sebastian. Your solution solved the problem too. – MZX Sep 02 '15 at 18:01
  • 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). – Eryk Sun Sep 03 '15 at 06:58
0

adding shell=True to command solved the problem.

MZX
  • 33
  • 3
  • 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](http://stackoverflow.com/a/25167402/4279). Look at [Windows questions in the subprocess tag info](http://stackoverflow.com/tags/subprocess/info) – jfs Sep 02 '15 at 17:11