2016-09-29 60 views
2

我想和subprocess.Popen()包含符号这个命令来执行被解释为一批连接运算符:怎么不逃与Python子的符号

COMMAND="c:\p\a.exe & python run.py" 
subprocess.Popen(COMMAND,cwd=wd,shell=False)` 

的符号&但被解释为一个参数的a.exe而不是作为批处理操作员。

解决方案1:在看到相关question,一个解决办法是设置shell=True但是,让“UNC路径,不支持”的错误,因为我的工作目录是远程的。此解决方案不能正常工作。

解决方案2:可执行文件a.exe应采用-inputDir参数来指定文件的远程位置并使用本地工作目录。我认为这个解决方案可以工作,但我可能没有可执行文件的源代码。

Solution3:我可以代替写c:\p\a.exe & python run.pycommand.bat然后用

COMMAND="c:\p\command.bat" 
subprocess.Popen(COMMAND,cwd=wd,shell=False)` 

莫非这种方法的工作?

解决方案4:我想解决这个变化只有subprocess.Popen()调用。可以做到吗?基于python Popen doc我怀疑是不可能的。请告诉我,我错了。

另请参阅this有关的问题。

UPDATE:

解决方案5:@mata建议使用Powershell的Popen(['powershell', '-Command', r'C:\p\a.exe; python run.py'])。这实际工作,但现在我必须处理略有不同的命令,和懒惰我已经决定要使用的解决方案3.

我最喜欢的解决方案是方案三,创建一个.bat文件,并调用它

COMMAND="c:\p\command.bat" 
subprocess.Popen(COMMAND,cwd=wd,shell=False) 
+0

你有没有考虑过自己检查返回代码? –

+0

@ IgnacioVazquez-Abrams我看不到在这里如何检查返回码。我不需要知道'a.exe'的返回码。 –

+0

我认为Ignacio运行一个命令,然后当完成运行其他,所以使用两个Popen调用,而不是一个,否则你受'cmd'不支持unc路径限制。如果可用,可以使用powershell:'Popen(['powershell','-Command',r'C:\ p \ a.exe; python run.py'])'而不是。 – mata

回答

0

我会用Solution 3

The & character is used to separate multiple commands on one command line. 
Cmd.exe runs the first command, and then the second command. 

在这种情况下,你可以只写你的批处理文件是这样的:

@echo off 
c:\p\a.exe 
python run.py 

此外,这是值得使用的cmd.exe时指出:

The ampersand (&), pipe (|), and parentheses () are special characters 
that must be preceded by the escape character (^) or quotation marks 
when you pass them as arguments. 
+1

我试过所有这些方法,这似乎更合理。使用'powershell -Command'会产生问题,因为它分割参数的方式不同,并且由于我不能忽略它的交互式提示框。现在我最喜欢传递'.bat',因为我也可以保留'Shell = False' –