[英]Why does my python program run with Powershell but not Bash? Using WSL
[英]Using WSL bash from within python
我正在使用 windows 10,在处理新项目时,我需要从 python(Windows python 解释器)中与 WSL(Windows 上的 Ubuntu)bash 进行交互。
我尝试使用子进程 python 库来执行命令。我所做的看起来像这样:
import subprocess
print(subprocess.check_call(['cmd','ubuntu1804', 'BashCmdHere(eg: ls)']))#not working
print(subprocess.check_output("ubuntu1804", shell=True).decode())#also not working
预期的行为是执行启动 wsl linux bash 的 ubuntu1804 命令,我想在其上执行我的“BashCmdHere”并将其结果检索到 python 但它只是冻结。 我究竟做错了什么? 或者怎么做?
太感谢了
找到了两种方法来实现这一点:
我的代码的正确版本如下所示
#e.g: To execute "ls -l"
import subprocess
print(subprocess.check_call(['wsl', 'ls','-l','MaybeOtherParamHere']))
我应该使用 wsl 从 windows aka bash 调用 linux shell,然后我的命令和参数在 subprocess 命令的分隔参数中。
我认为更简洁但可能更重的另一种方法是使用 PowerShell 脚本:
#script.ps1
param([String]$folderpath, [String]$otherparam)
Write-Output $folderpath
Write-Output $otherparam
wsl ls -l $folderpath $otherparam
然后在python中执行它并得到结果:
import subprocess
def callps1():
powerShellPath = r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe'
powerShellCmd = "./script.ps1"
#call script with argument '/mnt/c/Users/aaa/'
p = subprocess.Popen([powerShellPath, '-ExecutionPolicy', 'Unrestricted', powerShellCmd, '/mnt/c/Users/aaa/', 'SecondArgValue']
, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
rc = p.returncode
print("Return code given to Python script is: " + str(rc))
print("\n\nstdout:\n\n" + str(output))
print("\n\nstderr: " + str(error))
# Test
callps1()
谢谢你的帮助
关于什么:
print(subprocess.check_call(['ubuntu1804', 'run', 'BashCmdHere(eg: ls)'])) #also try without "run" or change ubuntu1804 to wsl
或者
print(subprocess.check_call(['cmd', '/c', 'ubuntu1804', 'run', 'BashCmdHere(eg: ls)']))#also try without "run" or change "ubuntu1804" to "wsl"
# I think you need to play with quotes here to produce: cmd /c 'ubuntu1804 run BashCmdHere(eg: ls)'
首先,尝试从cmd.exe
调用您的命令以查看正确的格式,然后将其转换为 Python。
os.system('bash')
我偶然发现了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.