Python subprocess.run('ls',shell = True)在Windows上不起作用

问题描述 投票:-3回答:1

导入子过程

subprocess.call('ls',shell = True)

输出:无法将“ ls”识别为内部或外部命令,可操作的程序或批处理文件。

python
1个回答
0
投票

ls不是Windows命令。它适用于Unixes。 Windows上的对等是dir。试试看:

import subprocess
subprocess.call('dir', shell=True)

[如果出于某些不可思议的原因,您必须致电ls,有很多方法可以拨打。

首先,Windows PowerShell支持调用ls,您只需要告诉Python执行它即可(以下路径在我的系统上是有效的:]

subprocess.call(r'c:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe ls', shell=True)

或者,Windows 10现在支持Windows与Linux之间的互操作性层,该层允许在Windows上使用Linux的环境(称为Windows的Windows子系统)。如果已安装,则使用它的方法之一是在Linux命令前加wsl

subprocess.call('wsl ls', shell=True)

最后,列出目录的最通用方法涉及使用内置的Python功能。例如,以下内容将为您提供当前目录的内容:

import os
os.listdir('.')
© www.soinside.com 2019 - 2024. All rights reserved.