【问题标题】:Python subprocess output read errorPython子进程输出读取错误
【发布时间】:2014-03-02 09:10:00
【问题描述】:

我有一个在终端上很好用的命令:

sudo tshark -V -l -i "any" -f 'udp port 4729'

我试图从我的 python 脚本中读取输出:

import subprocess
command = ['tshark', '-V', '-l', '-i', '"any"', '-f', '"udp port 4729"']  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
output, error = process.communicate()
print output

它不起作用。可能是在列表中写命令有些麻烦。

我收到错误:

gooman@ubuntu:~/workspace/glade_tests/src$ sudo ./main.py
tshark: Lua: Error during loading:
 [string "/usr/share/wireshark/init.lua"]:45: dofile has been disabled
Running as user "root" and group "root". This could be dangerous.
Capturing on "any"
tshark: The capture session could not be initiated (No such device exists).
Please check to make sure you have sufficient permissions, and that you have the proper interface or pipe specified.
0 packets captured

【问题讨论】:

  • 如果您将 sudo 添加到列表 ['sudo', 'tshark', ...] 并将 stderr = None, shell = True 添加到 Popen 会发生什么?
  • 你为什么使用subprocess.Popen而不是简单的subprocess.call?如果你使用subprocess.call 会发生什么?另外,请注意Popennew process (in which directory?) 开头,因此使用call 进行调试应该更容易。
  • 试试output = subprocess.check_output(command)
  • @User:不要使用shell=True 和列表参数。在大多数情况下这是一个错误。
  • @Gooman: 将"" 放入参数中,没有shell 来解释它们,即使用output = subprocess.check_output(shlex.split("""sudo tshark -V -l -i "any" -f 'udp port 4729'"""))

标签: python subprocess output tshark


【解决方案1】:

你的这个:

import subprocess

command = "sudo tshark -V -l -i "any" -f 'udp port 4729'"
try:
    output = subprocess.check_output(command, shell=True)
except subprocess.CalledProcessError as e:
    print "An error has been occured", e
    raise

print "The subprocess output:", output

也许,需要添加 stdout=subprocess.PIPE 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2014-02-10
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2012-06-07
    相关资源
    最近更新 更多