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


当前回答

典型的实施:

import subprocess

p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print line,
retval = p.wait()

事实上,你可以简单地忽略这些参数(stdout=和stderr=)并将像os.system()一样行事。

其他回答

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

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

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]

使用Python模块的Popen函数是运行Linux命令的最简单方式,Popen.communicate()函数将为您的命令提供输出。

import subprocess

..
process = subprocess.Popen(..)   # Pass command and arguments to the function
stdout, stderr = process.communicate()   # Get command output and error
..

如果您需要从 Python 笔记本电脑(如 Jupyter、Zeppelin、Databricks 或 Google Cloud Datalab)中拨打一个支票命令,您只能使用! 预定。

例如,

!ls -ilF

这里还有另一个区别,以前没有提到。

subprocess.Popen 执行 <命令> 作为一个子过程. 在我的情况下,我需要执行与另一个程序, <b> 沟通的 <a> 文件。

我尝试了子过程,执行成功了,但是 <b> 无法与 <a> 沟通,当我从终端运行时,一切都正常。

另外一个: (注意: kwrite 与其他应用程序不同,如果您尝试下面的 Firefox,结果将不相同。

如果你尝试 os.system(“kwrite”),程序流冻结,直到用户关闭 kwrite. 为了克服我尝试了 os.system(控制台 -e kwrite)。 这次程序继续流动,但 kwrite 成为控制台的子过程。

任何人运行基里特不是一个子过程(即在系统监控器中,它必须出现在树的左边)。

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