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

Chr*_*ris 7 python

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

String logfile = “/dev/log”
String cmd = “ls”
#try
  #execute cmd sending output to >> logfile
#catch sending caught error to >> logfile 
Run Code Online (Sandbox Code Playgroud)

Nad*_*mli 16

使用子进程模块是正确的方法:

import subprocess
logfile = open("/dev/log", "w")
output, error = subprocess.Popen(
                    ["ls"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
logfile.write(output)
logfile.close()
Run Code Online (Sandbox Code Playgroud)

EDIT 子进程希望命令作为列表运行"ls -l",你需要这样做:

output, error = subprocess.Popen(
                    ["ls", "-l"], stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
Run Code Online (Sandbox Code Playgroud)

稍微概括一下.

command = "ls -la"
output, error = subprocess.Popen(
                    command.split(' '), stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做,输出将直接转到日志文件,因此在这种情况下输出变量将为空:

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