[英]How can I open a terminal, execute a python script on it and then wait for the script to end?
Essentially, what I need to do is create a function that opens a new terminal, executes a python script on it and afterwards, waits for the script to end.本质上,我需要做的是创建一个函数来打开一个新终端,在其上执行一个 python 脚本,然后等待脚本结束。 From what I've been reading online, the best way to do this is to use the Python library subprocess.从我在网上阅读的内容来看,最好的方法是使用 Python 库子进程。 However, I've been finding it very difficult to use.但是,我发现它很难使用。 When I run the following code:当我运行以下代码时:
def function():
cmd = "gnome-terminal; python3 simple_action_client.py"
subprocess.check_output(cmd, shell=True)
print("I'm done!")
The print is executed after the terminal opens, meaning that the "check_output" function only waits for the first part of the cmd to be executed.打印在终端打开后执行,这意味着“check_output”函数只等待 cmd 的第一部分被执行。
Essentially, what I would like to do is the following:基本上,我想做的是以下内容:
def function():
terminal_command = "gnome-terminal"
script_command = "python3 script.py"
subprocess.run(terminal_command, shell = True)
subprocess.check_output(script_command, shell = True)
print("I'm done!")
But when I do something like this, the script doesn't run on the new terminal and I want it to run there.但是当我做这样的事情时,脚本不会在新终端上运行,我希望它在那里运行。
Is this possible to do?这是可能的吗? Thank you for the help!感谢您的帮助!
You are chaining commands to run in the local shell using您正在使用链接命令在本地 shell 中运行
def function():
cmd = "gnome-terminal; python3 simple_action_client.py"
subprocess.check_output(cmd, shell=True)
print("I'm done!")
You need to adjust the cmd line to tell gnome-terminal to execute the command您需要调整 cmd 行来告诉 gnome-terminal 执行命令
def function():
cmd = "gnome-terminal --wait -- python3 simple_action_client.py"
subprocess.check_output(cmd, shell=True)
print("I'm done!")
Notice the "--" instead of the ";"注意“--”而不是“;” and the "--wait" to wait for the command inside the shell to exit和“--wait”等待shell内的命令退出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.