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


当前回答

我倾向于与shlex一起使用子过程(以处理引用的绳子的逃避):

>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)

其他回答

您可以使用Popen,然后您可以检查程序的状态:

from subprocess import Popen

proc = Popen(['ls', '-l'])
if proc.poll() is None:
    proc.kill()

查看 subprocess.Popen。

如果您需要从您正在呼叫的命令中输出,那么您可以使用 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主要是为了增强的控制流,它提供了超过大多数系统阴道,仍然想要方便的访问其他阴道功能,如阴道管,字体名称野地图,环境变量扩展,并扩展 ~ 到用户的主目录。

import os
cmd = 'ls -al'
os.system(cmd)

如果你想返回命令的结果,你可以使用os.popen. 但是,这是由于版本 2.6 有利于子过程模块,其他答案已经覆盖得很好。

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

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

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

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

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

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

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

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

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]