我如何在Python中命名一个外部命令,就好像我把它写在一个<unk>或命令中?
当前回答
使用 subprocess.call:
from subprocess import call
# Using list
call(["echo", "Hello", "world"])
# Single string argument varies across platforms so better split it
call("echo Hello world".split(" "))
其他回答
Invoke 是一个 Python (2.7 和 3.4+) 任务执行工具和图书馆. 它提供清洁,高级别的 API 运行 Shell 命令:
>>> from invoke import run
>>> cmd = "pip install -r requirements.txt"
>>> result = run(cmd, hide=True, warn=True)
>>> print(result.ok)
True
>>> print(result.stdout.splitlines()[-1])
Successfully installed invocations-0.13.0 pep8-1.5.7 spec-1.3.1
与标准图书馆
使用子过程模块(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支持,所以它不像它以前那样令人惊叹。
如果您需要从您正在呼叫的命令中输出,那么您可以使用 subprocess.check_output (Python 2.7+)。
>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
请注意Shell参数。
如果阴道是真实的,指定的命令将通过阴道执行,这可能是有用的,如果你使用Python主要是为了增强的控制流,它提供了超过大多数系统阴道,仍然想要方便的访问其他阴道功能,如阴道管,字体名称野地图,环境变量扩展,并扩展 ~ 到用户的主目录。
经过一些研究,我有下面的代码,这对我来说非常好,它基本上在实时打印了标准输出和标准错误。
stdout_result = 1
stderr_result = 1
def stdout_thread(pipe):
global stdout_result
while True:
out = pipe.stdout.read(1)
stdout_result = pipe.poll()
if out == '' and stdout_result is not None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
def stderr_thread(pipe):
global stderr_result
while True:
err = pipe.stderr.read(1)
stderr_result = pipe.poll()
if err == '' and stderr_result is not None:
break
if err != '':
sys.stdout.write(err)
sys.stdout.flush()
def exec_command(command, cwd=None):
if cwd is not None:
print '[' + ' '.join(command) + '] in ' + cwd
else:
print '[' + ' '.join(command) + ']'
p = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
)
out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))
err_thread.start()
out_thread.start()
out_thread.join()
err_thread.join()
return stdout_result + stderr_result
我会建议使用子过程模块而不是os.system,因为它会让您逃脱,因此更安全。
subprocess.call(['ping', 'localhost'])