运行一个带有额外参数的Python程序。

huangapple go评论82阅读模式
英文:

Run a program with python with additional parameters

问题

我正在尝试在Python中运行带有参数-i ethernet -f udptshark.exe,但似乎无法弄清楚如何做到这一点。以下是代码的一部分:

from geolite2 import geolite2
import socket, subprocess

cmd = r"C:\Program Files\Wireshark\tshark.exe"

process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
my_ip = socket.gethostbyname(socket.gethostname())
reader = geolite2.reader()

尝试将命令更改为cmd = r"C:\Program Files\Wireshark\tshark.exe -i ethernet -f udp"不会起作用。

英文:

I am trying to run tshark.exe with the parameters -i ethernet -f udp, but I can't seem to figure out how to do that in Python. Here is a part of the code

from geolite2 import geolite2
import socket, subprocess

cmd = r"C:\Program Files\Wireshark\tshark.exe"

process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
my_ip = socket.gethostbyname(socket.gethostname())
reader = geolite2.reader() 

Running the same thing, but as cmd = r"C:\Program Files\Wireshark\tshark.exe -i ethernet -f udp won't work.

答案1

得分: 1

这里,可以在列表中指定参数。所以在你的情况下,

cmd = [r"C:\Program Files\Wireshark\tshark.exe", '-i', 'ethernet', '-f', 'udp']

应该可以工作。

英文:

From here, arguments can be specified in a list. So in your case,

cmd = [r"C:\Program Files\Wireshark\tshark.exe", '-i', 'ethernet', '-f', 'udp']

should work.

答案2

得分: 1

以下是翻译好的部分:

如果您需要从命令行传递参数给Python脚本,那么您可以使用sys模块和argv,如下所示:

import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

而在命令行中,您只需用空格分隔参数。例如:

python ex.py hello world

其中每个参数将返回:

print(sys.argv[0])
# 输出: ex.py

print(sys.argv[1])
# 输出: hello

print(sys.argv[2])
# 输出: world

更多信息可以在这里找到。

英文:

If you need to pass arguments from command line to a python script, then you can use the sys module with argv, like so:

import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

While with the command line you just separate the arguments with space. An example:

python ex.py hello world

Where each argument would return:

print(sys.argv[0])

> ex.py

print(sys.argv[1])

> hello

print(sys.argv[2])

> world

More info can be found here.

huangapple
  • 本文由 发表于 2020年1月3日 17:38:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定