在 python 中使用 WSL bash

Using WSL bash from within python

我正在使用 windows 10,在处理新项目时,我需要从 python (windows python 解释器).

我尝试使用子进程 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 但是它只是冻结。我究竟做错了什么 ?或者如何做到这一点?

非常感谢

怎么样:

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。

找到 2 种实现方法:

我的代码的正确版本如下所示

#e.g: To execute "ls -l"
import subprocess
print(subprocess.check_call(['wsl', 'ls','-l','MaybeOtherParamHere']))

我应该使用 wsl 从 windows 又名 bash 调用 linux shell 然后我的命令和参数在子进程命令的单独参数中。

另一种我认为更简洁但可能更重的方法是使用 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()

感谢您的帮助

os.system('bash')

我偶然发现了这个。