英文:
Run a program with python with additional parameters
问题
我正在尝试在Python中运行带有参数-i ethernet -f udp
的tshark.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论