简体   繁体   English

如何在Windows Powershell中从Python调用Shell脚本?

[英]How to call a shell script from Python in Windows Powershell?

I using a Python script to call a .sh script, as shown below 我使用Python脚本调用.sh脚本,如下所示

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

The first two lines of myScript.sh are myScript.sh的前两行是

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

I can run myScript.sh directly from Windows Powershell, but not from my Python script(run in Powershell). 我可以直接从Windows Powershell运行myScript.sh,但不能从我的Python脚本(在Powershell中运行)运行。 So, I know that myScript.sh is correct; 因此,我知道myScript.sh是正确的; however, I do not get output when run from my Python script On a different computer, this call worked fine, but now it doesn't. 但是,从我的Python脚本运行时,我没有得到输出。在另一台计算机上,此调用工作正常,但现在没有。 Any suggestions? 有什么建议么?

As @abarnet mentioned in his comment there is a COMSPEC environement variable that you can change to point at powershell rather than cmd : 正如@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

Which on my Windows machine returns: 我的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM