2013-10-08 87 views
1

我使用Python脚本调用脚本.SH,如下所示如何在Windows Powershell中从Python调用shell脚本?

ret = subprocess.call('sh ./myScript.sh '+file_a+' '+file_b+' '+str(self.counter), shell=True) 

myScript.sh的前两行是

#!/bin/bash 
echo "sh script opened" 

我可以直接从Windows Powershell的运行myScript.sh ,但不是从我的Python脚本(在Powershell中运行)。所以,我知道myScript.sh是正确的;但是,从我的Python脚本运行时,我不会得到输出在另一台计算机上,此调用运行正常,但现在不行。有什么建议么?

+0

什么你的'COMSPEC'环境变量?如果它是cmd(或未设置)而不是powershell,则Python将在cmd子shell中运行该命令,这将解释为什么它不会像在powershell中运行相同的命令那样提供相同的结果。 – abarnert

回答

1

正如在他的评论中提到@abarnet有一个COMSPEC environement变量,你可以在powershell而不是cmd改为指向:

import os 
import subprocess 

print os.environ["COMSPEC"] 
os.environ["COMSPEC"] = r"C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe" 
print os.environ["COMSPEC"] 
ret = subprocess.call('sh ./script.sh', shell=True) 
print ret 

这在我的Windows机器返回:

C:\Windows\system32\cmd.exe 
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe 
The term 'sh' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included , verify that the path is correct and try again. At line:1 char:3 
+ sh <<<< ./script.sh 
    + CategoryInfo   : ObjectNotFound: (sh:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException 
相关问题