在 Python 中,执行存储在字符串中的本地 Linux 命令同时捕获任何可能抛出的异常并将 Linux 命令的输出和任何捕获的错误记录到公共(public)日志文件的最简单方法是什么?
String logfile = “/dev/log”
String cmd = “ls”
#try
#execute cmd sending output to >> logfile
#catch sending caught error to >> logfile
最佳答案
使用 subprocess模块是正确的方法:
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()
关于python - 在 Python 中,执行存储在字符串中的本地 Linux 命令的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1394198/