在蟒蛇另一个目录中运行一个批处理文件 [英] Running a batch file in another directory in python

查看:150
本文介绍了在蟒蛇另一个目录中运行一个批处理文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要运行位于MyFolder中 mybat.bat 文件,该文件是从当前目录不同。我用下面的code:

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"

我要指出,如果我取代 mybat 与路径中的其他程序,如记事本它工作绝对没问题。

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

推荐答案

工作目录仅在子进程改变即 CWD = MyFolder中不作 os.path.join(MyFolder中,mybat.bat)可用。尝试:

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)

您可以使用%〜DP0 你的蝙蝠文件里面,得到其中蝙蝠文件驻留而不是 CWD = MyFolder中为<一个目录href=\"http://stackoverflow.com/questions/32358818/running-a-batch-file-in-another-directory-in-python#comment52609529_32359372\">@eryksun建议。

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

这篇关于在蟒蛇另一个目录中运行一个批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆