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


当前回答

还有铅

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

其他回答

2015 年更新: Python 3.5 添加了 subprocess.run 比 subprocess.Popen 更容易使用。

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

从 OpenStack Neutron 中获取网络 ID:

#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read()  /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)

新网列表

+--------------------------------------+------------+------+
| ID                                   | Label      | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1      | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External   | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal   | None |
+--------------------------------------+------------+------+

印刷输出(networkId)

27a74fcd-37c0-4789-9414-9531b7e3f126

我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。

subprocess.call(['ping', 'localhost'])

使用副过程。

或者一个非常简单的命令:

import os
os.system('cat testfile')

如果您在命令中不使用用户输入,您可以使用以下操作:

from os import getcwd
from subprocess import check_output
from shlex import quote

def sh(command):
    return check_output(quote(command), shell=True, cwd=getcwd(), universal_newlines=True).strip()

用它作为

branch = sh('git rev-parse --abbrev-ref HEAD')

shell=True 将扫描一个阴道,所以你可以使用管道和这样的阴道事物 sh('ps auxibh grep python'). 这是非常方便的运行硬编码命令和处理其输出。

但这不是安全的用户输入,从文档:

安全考虑 与其他某些字符功能不同,此实施将永远不会随意称为系统字符,这意味着所有字符,包括字符字符字符,都可以安全地转移到儿童过程,如果字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符字符

In [50]: timeit("check_output('ls -l'.split(), universal_newlines=True)", number=1000, globals=globals())
Out[50]: 2.6801227919995654

In [51]: timeit("check_output('ls -l', universal_newlines=True, shell=True)", number=1000, globals=globals())
Out[51]: 3.243950183999914