python - 如何在 Windows Powershell 中从 Python 调用 shell 脚本?

标签 python bash sh

我使用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/

相关文章:

linux - 通过按特定按钮停止脚本(在脚本处理它时收听 STDIN)

c - 有没有办法阻止 sh/bash 执行命令替换?

python - 获取python中子目录的名称(不是完整路径)

python - 使用 Python 和 sndhdr 模块检查文件是否为音频文件

linux - 如何删除两种模式之间的 block 文本?

arrays - Bash,调用值时使用变量作为关联数组的名称

python - Sublime text 不断删除文档中的表格

python - 当映射不是一对一时,ctypes 如何将 C 结构体成员映射到 Python 类 _fields_?

bash:评论一个长管道

bash - 在 sh shell 中找不到源命令