在Python中,执行存储在字符串中的本地Linux命令的最佳方法是什么?
在Python中,如何以最简单的方式执行一个存储在字符串中的本地Linux命令,同时捕获可能出现的错误,并将Linux命令的输出和任何捕获到的错误记录到一个公共日志文件中呢?
String logfile = “/dev/log”
String cmd = “ls”
#try
#execute cmd sending output to >> logfile
#catch sending caught error to >> logfile
3 个回答
-3
可以看看 commands
模块。
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()
在 except
后面指定 Exception
作为异常类,意思是告诉 Python 要捕捉所有可能出现的错误。
0
subprocess是最好的模块来实现这个功能。
你可以用不同的方法来运行你的脚本,可以在不同的线程中运行,也可以在同一个线程中等待每个命令完成后再继续。建议你查看一下完整的文档,里面有很多有用的信息:
16
使用 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()
编辑 subprocess 模块需要把命令放在一个列表里,所以如果你想运行 "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()