首页 > 解决方案 > 在 python 中使用 WSL bash

问题描述

我正在使用 Windows 10,并且在处理一个新项目时,我需要从 python(windows python 解释器)中与 WSL(windows 上的 Ubuntu)bash 交互。

我尝试使用 subprocess 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 命令,该命令启动一个 wsl linux bash,我想在该命令上执行我的 'BashCmdHere' 并将其结果检索到 python,但它只是冻结。我究竟做错了什么 ?或如何做到这一点?

太感谢了

标签: pythonwindowsbashwindows-subsystem-for-linux

解决方案


找到了两种方法来实现这一点:

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

#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()

谢谢你帮忙


推荐阅读