在Python中,执行存储在字符串中的本地Linux命令的最佳方式是什么?

在Python中,执行存储在字符串中的本地Linux命令的最佳方式是什么?,python,Python,在Python中,执行以字符串形式存储的本地Linux命令的最简单方法是什么,同时捕获抛出的任何潜在异常,并将Linux命令的输出和捕获的任何错误记录到公共日志文件中 String logfile = “/dev/log” String cmd = “ls” #try #execute cmd sending output to >> logfile #catch sending caught error to >> logfile 子流程是最好的模块 您可以使用

在Python中,执行以字符串形式存储的本地Linux命令的最简单方法是什么,同时捕获抛出的任何潜在异常,并将Linux命令的输出和捕获的任何错误记录到公共日志文件中

String logfile = “/dev/log”
String cmd = “ls”
#try
  #execute cmd sending output to >> logfile
#catch sending caught error to >> logfile 

子流程是最好的模块

您可以使用不同的方式运行脚本,可以在不同的线程中运行,也可以在相同的线程中等待每个命令完成。检查所有有用的文档:

使用模块是正确的方法:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
logfile.write(output)
logfile.close()
编辑 子流程希望命令作为列表,因此要运行“ls-l”,需要执行以下操作:

output, error = subprocess.Popen(
                    ["ls", "-l"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
概括一下

command = "ls -la"
output, error = subprocess.Popen(
                    command.split(' '), stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
或者,您可以这样做,输出将直接转到日志文件,因此在这种情况下,输出变量将为空:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=logfile,
                    stderr=subprocess.PIPE).communicate()

检查
命令
模块

    import commands
    f = open('logfile.log', 'w')
    try:
        exe = 'ls'
        content = commands.getoutput(exe)
        f.write(content)
    except Exception, text:
        f.write(text)
    f.close()

Exception
之后指定
Exception
作为Exception类将告诉Python捕获所有可能的异常。

如果您在投票前给出不同意注释的原因,将会有更多的用处。你的观点是什么?你知道为什么这种方法似乎对“ls”和“dir”这样的cmd字符串有效,但却对“python-h”和“apt get-h”这样的字符串生成操作错误吗?@Chris,当然。我将在答案中添加细节