繁体   English   中英

python中如何使用subprocess.run方法?

[英]How to use subprocess.run method in python?

我想使用 python 运行外部程序,但收到错误消息说我没有该文件

我写的代码:

import subprocess

subprocess.run(["ls", "-l"])

Output:

Traceback (most recent call last):
  File "C:\Users\hahan\desktop\Pythonp\main.py", line 3, in <module>
    subprocess.run(["ls", "-l"])
  File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\hahan\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1438, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

我希望它返回该目录中的文件

堆栈跟踪表明您正在使用 Windows 作为操作系统。 除非使用像 CygWin 这样的东西,否则通常不会在ls机器上找到它。

相反,请尝试以下选项之一:

# use python's standard library function instead of invoking a subprocess
import os
os.listdir()
# invoke cmd and call the `dir` command
import subprocess
subprocess.run(["cmd", "/c", "dir"])
# invoke PowerShell and call the `ls` command, which is actually an alias for `Get-ChildItem`
import subprocess
subprocess.run(["powershell", "-c", "ls"])

ls不是 Windows 命令。 windows 模拟是dir ,所以你可以做类似的事情

import subprocess
subprocess.run(['cmd', '/c', 'dir'])

但是,如果您真的只是想列出一个目录,那么使用os.listdir()

import os
os.listdir()

pathlib

from pathlib import Path
list(Path().iterdir())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM