[英]How automatically change to different program when a button is pressed in Python
I'd like for my first program to automatically switch over to a second program when a button is pressed. 我希望我的第一个程序在按下按钮时自动切换到第二个程序。
I tried break and sys.exit() but that put me back at the command line, which I don't want to I'm trying to eliminate having to use the mouse and keyboard to change to a different program. 我尝试了break和sys.exit(),但是那让我回到了命令行,我不想这么做,我想消除使用鼠标和键盘来更改为其他程序的麻烦。
The programs are for a microcomputer that will be doing the same tasks many times a day; 这些程序用于一台微型计算机,该计算机每天将执行多次相同的任务; I don't want to have a keyboard or mouse connected after the installation.
安装后,我不想连接键盘或鼠标。
You can use the subprocess
module for this. 您可以为此使用
subprocess
模块。 Create a Popen
object for the script you want triggered, and then exit the parent process without waiting for the child to complete: 为要触发的脚本创建一个
Popen
对象,然后退出父进程,而无需等待子进程完成:
import subprocess
import sys
def on_button_pressed():
subprocess.Popen(["path/to/script", "arg1", "arg2"], shell=False)
sys.exit()
You may encapsulate the second program in a function, and call the function from your first program. 您可以将第二个程序封装在一个函数中,然后从第一个程序中调用该函数。 Alternatively, if the second program resides in its own module, you may import that module.
或者,如果第二个程序位于其自己的模块中,则可以导入该模块。 Importing the module will execute the code inside of it.
导入模块将在其中执行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.