subprocess.popen 后执行下一行代码

Executing the next line of code after subprocess.popen

我正在使用 Popen 执行 Tcpdump 命令。在我的代码中,popen 行运行但它不执行 popen 代码行之后的下一行代码。为什么会这样,我该如何解决?谢谢

from subprocess import Popen, PIPE
import os
import time

pw ='12345678'
process = Popen(['sudo', '-S', 'tcpdump', '-i', 'wlp1s0', 'udp', 'port 8308', '-w', 'trace.pcap'], stdout=PIPE,universal_newlines=True,stdin=PIPE)
process.communicate(pw + '\n')[1]
print("Command ran")
time.sleep(3)

这里没有打印"Command ran"。

process.communicate 等待进程终止。

如果你想在不等待终止的情况下将输入发送到进程,请使用 process.stdin

process.stdin.write(password + "\n")

tcpdump 除非您发送 SIGINT 信号,否则不会以您的参数终止。

Tcpdump will, if not run with the -c flag, continue capturing packets until it is interrupted by a SIGINT signal (generated, for example, by typing your interrupt character, typically control-C) or a SIGTERM signal (typically generated with the kill(1) command); if run with the -c flag, it will capture packets until it is interrupted by a SIGINT or SIGTERM signal or the specified number of packets have been processed.

您可以在参数中包含 -c 标志。