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


当前回答

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

其他回答

作为一个例子(在Linux):

import subprocess
subprocess.run('mkdir test.dir', shell=True)

这在当前目录中创建 test.dir. 请注意,这也是有效的:

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

使用 os.system 的同等代码是:

import os
os.system('mkdir test.dir')

最好的做法是使用子过程而不是OS,与.run 受欢迎的.call. 所有你需要知道的子过程在这里. 此外,请注意,所有的 Python 文档都可以从这里下载. 我下载了 PDF 包装为.zip. 我提到这一点,因为有一个好概述的OS 模块在 tutorial.pdf (页面 81 ) 。 此外,它是一个授权的资源的 Python 编码器。

我会推荐下面的“运行”方法,它会帮助我们获得标准输出、标准错误和输出状态作为词典;这个词典的呼叫者可以通过“运行”方法阅读词典返回,以了解过程的实际状态。

  def run (cmd):
       print "+ DEBUG exec({0})".format(cmd)
       p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
       (out, err) = p.communicate()
       ret        = p.wait()
       out        = filter(None, out.split('\n'))
       err        = filter(None, err.split('\n'))
       ret        = True if ret == 0 else False
       return dict({'output': out, 'error': err, 'status': ret})
  #end

在Linux中,如果您想打电话给一个将独立执行的外部命令(在Python脚本结束后将继续运行),您可以使用一个简单的字符串作为任务插槽或命令中的命令。

例如,Task Spooler:

import os
os.system('ts <your-command>')

關於Task Spooler(TS)的評論:

您可以设置要运行的竞争对手过程的数量(“插槽”)与: ts -S <插槽的号码> 安装 ts 不需要管理特权. 您可以从源头下载并编写一个简单的创建,将其添加到您的路径,并完成。

您可以使用 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()

subprocess.check_call 是方便的,如果你不想测试返回值。