我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?


当前回答

os.popen() 是执行命令的最简单和最安全的方式. 您可以在命令行上执行任何命令. 此外,您还将能够使用 os.popen().read() 捕获命令的输出。

你可以这样做:

import os
output = os.popen('Your Command Here').read()
print (output)

例如,您列出当前目录中的所有文件:

import os
output = os.popen('ls').read()
print (output)
# Outputs list of files in the directory

其他回答


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。

您总是从您的程序中获取比特结果. 如果您想像正常字符串一样使用它,则设置文本=真实。

下面是如何呼叫外部程序的概述,包括其优点和缺点:

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 /”可以删除整个文件系统。

查看Python图书馆的“快速”图书馆,也。

它允许对外程序 / 命令的互动控制,甚至 ssh, ftp, telnet 等。

child = pexpect.spawn('ftp 192.168.0.24')

child.expect('(?i)name .*: ')

child.sendline('anonymous')

child.expect('(?i)password')

与标准图书馆

使用子过程模块(Python 3):

import subprocess
subprocess.run(['ls', '-l'])

但是,更复杂的任务(管道,输出,输入等)可以是无聊的构建和写作。

注意 Python 版本: 如果您仍然使用 Python 2, subprocess.call 以类似的方式运行。

ProTip: shlex.split 可以帮助您打破运行命令、呼叫和其他子过程功能,如果您不希望(或您不能!)以列表的形式提供它们:

import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))

与外部依赖

如果你不注意外部依赖,使用铅:

from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())

它是最好的子处理器. 它是跨平台,即它在Windows和Unix类似的系统上运行。

另一个受欢迎的图书馆是:

from sh import ifconfig
print(ifconfig('wlan0'))

然而,sh下降了Windows支持,所以它不像它以前那样令人惊叹。

使用:

import os

cmd = 'ls -al'

os.system(cmd)

os - 此模块提供一个可携带的方式来使用操作系统依赖的功能。

对于更多的 OS 功能,这里是文档。