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


当前回答

import subprocess

p = subprocess.run(["ls", "-ltr"], capture_output=True)
print(p.stdout.decode(), p.stderr.decode())

网上尝试

其他回答

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

在这里获取更多信息

对于 Python 3.5+ 而言,建议您从子过程模块中使用运行函数,这将返回一个完整的过程对象,您可以轻松地获得输出和返回代码。

from subprocess import PIPE, run

command = ['echo', 'hello']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
print(result.returncode, result.stdout, result.stderr)

与标准图书馆

使用子过程模块(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支持,所以它不像它以前那样令人惊叹。

下面是我的两个百分点:在我看来,这是处理外部命令时最好的做法......

这些是执行方法的回报值......

pass, stdout, stderr = execute(["ls","-la"],"/home/user/desktop")

这是执行方法......

def execute(cmdArray,workingDir):

    stdout = ''
    stderr = ''

    try:
        try:
            process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
        except OSError:
            return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']

        for line in iter(process.stdout.readline, b''):

            try:
                echoLine = line.decode("utf-8")
            except:
                echoLine = str(line)

            stdout += echoLine

        for line in iter(process.stderr.readline, b''):

            try:
                echoLine = line.decode("utf-8")
            except:
                echoLine = str(line)

            stderr += echoLine

    except (KeyboardInterrupt,SystemExit) as err:
        return [False,'',str(err)]

    process.stdout.close()

    returnCode = process.wait()
    if returnCode != 0 or stderr != '':
        return [False, stdout, stderr]
    else:
        return [True, stdout, stderr]

我为此写了一本图书馆,shell.py。

它基本上是现在的旋转器和旋转器,它还支持旋转命令,所以你可以在Python中更容易进行连锁命令,所以你可以做这样的事情:

ex('echo hello shell.py') | "awk '{print $2}'"