我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
Python 3.5 以上
import subprocess
p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())
网上尝试
其他回答
TL;DR 2021年
import subprocess
subprocess.run("ls -a", shell=True)
注意:这是对你的问题的准确答案 - 执行命令
就像在沙子里
偏好之路
如果可能的话,移除箭头顶部并直接运行命令(需要列表)。
import subprocess
subprocess.run(["help"])
subprocess.run(["ls", "-a"])
检查输出
下列代码本身就是:
import subprocess
result = subprocess.run(["ls", "-a"], capture_output=True, text=True)
if "stackoverflow-logo.png" in result.stdout:
print("You're a fan!")
else:
print("You're not a fan?")
查看返回代码
if result.returncode == 127: print("The program failed for some weird reason")
elif result.returncode == 0: print("The program succeeded")
else: print("The program failed unexpectedly")
result.check_returncode()
result = subprocess.run(..., check=True)
result = subprocess.run(..., stderr=subprocess.STDOUT)
使用shell=False 与论点字符串
import subprocess
import shlex
subprocess.run(shlex.split("ls -a"))
常见问题
FileNotFoundError: [Errno 2] 没有此类文件或目录: 'ls -a': 'ls -a'
此分類上一篇: NoneType [...]
确保您已设置 capture_output=True。
您总是从您的程序中获取比特结果. 如果您想像正常字符串一样使用它,则设置文本=真实。
使用 subprocess.call:
from subprocess import call
# Using list
call(["echo", "Hello", "world"])
# Single string argument varies across platforms so better split it
call("echo Hello world".split(" "))
下面是如何呼叫外部程序的概述,包括其优点和缺点:
os.system 将命令和论点转移到您的系统的阴道. 这很好,因为您实际上可以以这种方式同时运行多个命令,并设置管道和输入/输出重定向。 例如: os.system(“some_command < input_file♰ another_command > output_file”) 但是,虽然这是方便的,您必须手动处理阴道字符的逃避,如空间,和
副过程模块应该是你所使用的。
最后,请注意,对于你通过的所有方法,最终命令将由丝带执行,你负责逃避它。 有严重的安全影响,如果你通过的丝带的任何部分不能完全信任。 例如,如果用户进入某些 / 任何部分的丝带. 如果你不确定,只使用这些方法的连续。
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
想象一下,用户输入了一些“我的妈妈不喜欢我&rm -rf /”可以删除整个文件系统。
您可以使用Popen,然后您可以检查程序的状态:
from subprocess import Popen
proc = Popen(['ls', '-l'])
if proc.poll() is None:
proc.kill()
查看 subprocess.Popen。
只需添加到讨论中,如果您使用 Python 控制台,您可以从 IPython 呼叫外部命令,而在 IPython 快速时,您可以通过预定“!”。您也可以将 Python 代码与 Shell 结合起来,并将 Shell 脚本的输出分配给 Python 变量。
例如:
In [9]: mylist = !ls
In [10]: mylist
Out[10]:
['file1',
'file2',
'file3',]
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从终端/命令行调用VS代码编辑器
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出