【发布时间】:2021-11-16 14:35:34
【问题描述】:
我正在尝试运行一个简单的命令,该命令在执行我的自动化测试之前启动端口转发,但每次都会挂起。
最终目标是在会话结束时设置端口转发、获取 PID 并终止端口转发。
我在macOS 并使用Python 3.9.7 并尝试在PyCharm IDE 内部执行此操作。
这里是sn-p的代码:
def setup_port_forward():
# command
command = 'kubectl port-forward api_service 8080:80 -n service_name'
# shell
shell_script = subprocess.Popen(command,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=True)
# extract
try:
stdout, stderr = shell_script.communicate(timeout=15)
pid = int(stdout.decode().strip().split(' ')[-1])
except subprocess.TimeoutExpired:
shell_script.kill()
yield
# kill session
os.kill(pid, signal.SIGTERM)
我不会假装知道它的作用或工作原理,因为我还在学习 python。
这是我看过的一些主题:
Python Script execute commands in Terminal
python subprocess.Popen hanging
Python Script execute commands in Terminal
Python hangs when executing a shell script that runs a process as a daemon
https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate
许多线程说在 shell 脚本中使用 subprocess.PIPE 可能会导致问题,但同样,在另一个线程上,关于如何获取 PID,这是使用的方法。
我尝试使用不同线程中建议的不同方式:
command = 'kubectl port-forward api_service 8080:80 -n service_name'
# 1
os.system(command)
# 2
subprocess.Popen(command).communicate
# 3
subprocess.run(command)
# 4
subprocess.call(command)
# 5
commands.getstatusoutput(command)
他们都挂了。运行它是终端,它工作正常。
【问题讨论】:
-
“PF”是什么意思?
-
@mkrieger1 代表端口转发。我会改变它:)
-
yield属于哪里?你不能只在函数之外写yield。 -
@mkrieger1 没错,它在函数内部。我再次更新了这个问题。 :)
-
不清楚超时应该在这里实现什么。进程是否输出您需要的信息?
Popen已经知道它创建的进程的pid。
标签: python subprocess