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

标签 python

在 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/

相关文章:

python - python写文件处理编码

python - 如何从字典中减去值

python - 如果您不知道日期输入的格式,如何格式化日期字符串?

python - 如何在python中旋转 turtle 形状

python - 使用Python实现Switch : 'null is not callable'

python - 如果 Flask View 中出现错误,如何使 Redis 缓存对象失效或删除

python - 边界处有约束的样条

Python ml 引擎预测 : How can I make a googleapiclient. discovery.build 持久?

python - Scipy 优化最小化不可靠

python - 键盘控制 Python