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

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

Run a program with python with additional parameters

问题

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

  1. from geolite2 import geolite2
  2. import socket, subprocess
  3. cmd = r"C:\Program Files\Wireshark\tshark.exe"
  4. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  5. my_ip = socket.gethostbyname(socket.gethostname())
  6. 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

  1. from geolite2 import geolite2
  2. import socket, subprocess
  3. cmd = r"C:\Program Files\Wireshark\tshark.exe"
  4. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  5. my_ip = socket.gethostbyname(socket.gethostname())
  6. 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

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

  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,

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

should work.

答案2

得分: 1

以下是翻译好的部分:

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

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

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

  1. python ex.py hello world

其中每个参数将返回:

  1. print(sys.argv[0])
  2. # 输出: ex.py
  3. print(sys.argv[1])
  4. # 输出: hello
  5. print(sys.argv[2])
  6. # 输出: 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:

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

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

  1. python ex.py hello world

Where each argument would return:

  1. print(sys.argv[0])

> ex.py

  1. print(sys.argv[1])

> hello

  1. 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:

确定