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


当前回答

os.system 不允许您存储结果,所以如果您想要存储结果在某些列表或某些东西,一个 subprocess.call 工作。

其他回答

我为此写了一本图书馆,shell.py。

它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:

ex('echo hello shell.py') | "awk '{print $2}'"


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。

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

您可以使用 Popen 从子过程模块运行任何命令。

from subprocess import Popen

首先,一个命令对象是创建的,所有你想要运行的论点。 例如,在下面的剪辑中,指令对象是由所有论点组成的:

cmd = (
        "gunicorn "
        "-c gunicorn_conf.py "
        "-w {workers} "
        "--timeout {timeout} "
        "-b {address}:{port} "
        "--limit-request-line 0 "
        "--limit-request-field_size 0 "
        "--log-level debug "
        "--max-requests {max_requests} "
        "manage:app").format(**locals())

然后这个命令对象与Popen一起使用,以启动一个过程:

process = Popen(cmd, shell=True)

这个过程也可以根据任何信号结束,使用下面的代码线:

Popen.terminate(process)

你可以等到完成上述命令的执行:

process.wait()

有很多不同的图书馆,允许您使用Python呼叫外部命令. 对于每个图书馆,我给了一个描述,并显示了一个例子呼叫外部命令. 我使用的命令作为例子是ls -l(列出所有文件)。 如果你想了解更多关于任何图书馆,我列出并链接到文件的每一个。

来源

这些都是图书馆

希望这会帮助你做出决定哪个图书馆使用:)

副过程

subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command

os 用于“操作系统依赖功能”。 它也可以用来呼叫与 os.system 和 os.popen 的外部命令(注:也有 subprocess.popen)。 os 总是会运行盾牌,并且对于那些不需要或不知道如何使用 subprocess.run 的人来说是一个简单的替代方案。

os.system("ls -l") # Run command
os.popen("ls -l").read() # This will run the command and return any output

饰 sh

sh 是一个子过程界面,允许您呼叫程序,就好像它们是功能。

sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function

ls_cmd = plumbum.local("ls -l") # Get command
ls_cmd() # Run command

佩克斯

pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')

织物

fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output

发送

r = envoy.run("ls -l") # Run command
r.std_out # Get output

命令

使用:

import subprocess

p = subprocess.Popen("df -h", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
print p.split("\n")

它提供良好的产量,更容易与:

['Filesystem      Size  Used Avail Use% Mounted on',
 '/dev/sda6        32G   21G   11G  67% /',
 'none            4.0K     0  4.0K   0% /sys/fs/cgroup',
 'udev            1.9G  4.0K  1.9G   1% /dev',
 'tmpfs           387M  1.4M  386M   1% /run',
 'none            5.0M     0  5.0M   0% /run/lock',
 'none            1.9G   58M  1.9G   3% /run/shm',
 'none            100M   32K  100M   1% /run/user',
 '/dev/sda5       340G  222G  100G  69% /home',
 '']