python - 在 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,但它只是冻结。我究竟做错了什么 ?或如何做到这一点?
太感谢了
解决方案
找到了两种方法来实现这一点:
我的代码的正确版本如下所示
#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()
谢谢你帮忙
推荐阅读
- java - 如何在 JSP 中动态检索和显示图像?
- javascript - 如何向 React-Select 添加更多可搜索选项?
- php - Codeigniter - 像查询不使用搜索字符串
- javascript - 获取 URL 的最后两个参数 - javascript
- xamarin - 属性绑定中的跨度文本绑定错误
- regex - Python正则表达式抛出AttributeError:'NoneType'对象没有属性'group'
- python - Raspberry Pi:“ValueError:无法解码任何 JSON 对象”
- java - 单击图像视图时开始新视频
- python - 将字符串格式化为仅在 python 中的单词之间有 n 个空格
- windows - 搜索文件并更改为另一个