Python subprocess.run('ls',shell=True) 不适用于 Windows [英] Python subprocess.run('ls',shell=True) not working on windows

查看:44
本文介绍了Python subprocess.run('ls',shell=True) 不适用于 Windows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import subprocess

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

输出:

'ls' is not recognized as an internal or external command, operable program or batch file.

推荐答案

ls 不是 Windows 命令.它适用于 Unix.它在 Windows 上的对应物是 dir.试试看:

ls is not a Windows command. It works on Unixes. Its counterpart on Windows is dir. Try iy out:

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

如果出于某种神秘的原因,您必须调用 ls,有很多方法可以这样做.

If, for some arcane reason, you have to call ls there is a bunch of ways to do so.

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

Firstly, Windows PowerShell supports calling ls, you just have to tell Python to execute it (the path below is valid on my system):

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

或者,Windows 10 现在支持 Windows 和 Linux 之间的互操作层,允许在 Windows 上使用 Linux 的环境(称为 Windows Subsystem for Linux).如果您安装了它,使用它的一种方法是在 Linux 命令之前使用 wsl:

Alternatively, Windows 10 now supports an interoperability layer between Windows and Linux, which allows to use Linux's environment on Windows (called Windows Subsystem for Linux). If you have it installed, one of the way to use it is to precede Linux command with wsl:

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

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

Lastly, the most universal way to list the directory would involve using the built-in Python functionality. E.g the following would give you the content of the current directory:

import os
os.listdir('.')

这篇关于Python subprocess.run('ls',shell=True) 不适用于 Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆