簡體   English   中英

從 python 中使用 WSL bash

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM