Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中的另一个目录中运行批处理文件_Python_Windows_Batch File_Subprocess - Fatal编程技术网

在python中的另一个目录中运行批处理文件

在python中的另一个目录中运行批处理文件,python,windows,batch-file,subprocess,Python,Windows,Batch File,Subprocess,我想运行位于MyFolder中的与当前目录不同的mybat.bat文件。我使用了以下代码: subprocess.Popen(["mybat", MyArg], cwd=MyFolder, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) 但是,我得到以下错误:

我想运行位于MyFolder中的与当前目录不同的
mybat.bat
文件。我使用了以下代码:

subprocess.Popen(["mybat", MyArg],
                  cwd=MyFolder,
                  stdout=subprocess.PIPE,
                  stderr=subprocess.PIPE,
                  stdin=subprocess.PIPE)
但是,我得到以下错误:

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

我应该提到的是,如果我用路径中的另一个程序(如
notepad
)替换
mybat
,它绝对可以正常工作

将shell=True添加到命令解决了问题。

工作目录仅在子进程中更改,即,
cwd=MyFolder
不会使
os.path.join(MyFolder,“mybat.bat”)
可用。尝试:

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

您可以代替
cwd=MyFolder
as.

Yes。我的文件夹中确实有mybat.bat文件。如果错误仍然存在,您可以提供显式的
.bat
扩展名和bat文件的完整路径,从而避免使用
shell=True
。看见看,谢谢,塞巴斯蒂安。您的解决方案也解决了这个问题。正确编写的批处理文件通常不需要设置
cwd
来查找与自身相关的文件。它应该使用
%~dp0
获取批处理文件的完全限定路径,即.bat文件的[d]驱动和[p]路径(命令行参数0)。