2013-10-08 86 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 
相關問題