我使用Python脚本调用.sh脚本,如下所示
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 脚本运行时,我没有得到输出。在另一台计算机上,此调用工作正常,但现在不行。有什么建议吗?
最佳答案
正如 @abarnet 在他的评论中提到的,有一个 COMSPEC
环境变量,您可以将其更改为指向 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
关于python - 如何在 Windows Powershell 中从 Python 调用 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19257917/