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


当前回答

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

其他回答

我写了一本小图书馆来帮助这个使用案例:

HTTPS://pypi.org/project/citizenshell/

可以使用安装

pip install citizenshell

然后使用如下:

from citizenshell import sh
assert sh("echo Hello World") == "Hello World"

您可以将标准输出与标准错误分开,并以以下方式提取输出代码:

result = sh(">&2 echo error && echo output && exit 13")
assert result.stdout() == ["output"]
assert result.stderr() == ["error"]
assert result.exit_code() == 13

而且很酷的是,在开始处理输出之前,你不需要等待底层的裂缝出发:

for line in sh("for i in 1 2 3 4; do echo -n 'It is '; date +%H:%M:%S; sleep 1; done", wait=False)
    print ">>>", line + "!"

将按行按行按行按行按行按行按行按行按行。

>>> It is 14:24:52!
>>> It is 14:24:53!
>>> It is 14:24:54!
>>> It is 14:24:55!

更多例子可以找到 https://github.com/meuter/citizenshell

只需添加到讨论中,如果您使用 Python 控制台,您可以从 IPython 呼叫外部命令,而在 IPython 快速时,您可以通过预定“!”。您也可以将 Python 代码与 Shell 结合起来,并将 Shell 脚本的输出分配给 Python 变量。

例如:

In [9]: mylist = !ls

In [10]: mylist
Out[10]:
['file1',
 'file2',
 'file3',]

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

os.system 是 OK,但类型的日期. 它也不是很安全. 相反,尝试 subprocess. subprocess 不直接呼叫 sh 因此比 os.system 更安全。

在这里获取更多信息

我倾向于与shlex一起使用子过程(以处理引用的绳子的逃避):

>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)