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


当前回答

os.popen() 是执行命令的最简单和最安全的方式. 您可以在命令行上执行任何命令. 此外,您还将能够使用 os.popen().read() 捕获命令的输出。

你可以这样做:

import os
output = os.popen('Your Command Here').read()
print (output)

例如,您列出当前目录中的所有文件:

import os
output = os.popen('ls').read()
print (output)
# Outputs list of files in the directory

其他回答

使用副过程。

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

import os
os.system('cat testfile')

使用:

import os

cmd = 'ls -al'

os.system(cmd)

os - 此模块提供一个可携带的方式来使用操作系统依赖的功能。

对于更多的 OS 功能,这里是文档。

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

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

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

这就是我如何运行我的命令. 这个代码有你需要的一切

from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()