在python中使用WSL bash

时间:2019-08-28 13:20:17

标签: python windows bash windows-subsystem-for-linux

我正在使用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

预期的行为是执行ubuntu1804命令,该命令启动我要在其上执行“ BashCmdHere”的wsl linux bash并将其结果检索到python,但是它只是冻结。我究竟做错了什么 ?或如何执行此操作?

非常感谢您

2 个答案:

答案 0 :(得分:1)

那又怎么样:

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。

答案 1 :(得分:1)

找到了两种方法可以实现这一目标:

我的代码的正确版本如下

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

我应该使用wsl从Windows aka 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()

感谢您的帮助