现在我有两个python脚本“ GUI.py”和“ main.py”。 “ GUI.py”是使用pyQt5编写的。 首先,我打开一个cmd窗口并运行“ python GUI.py”。它将打开一个窗口,其中包含一个名为“ connect”的按钮。每当我单击按钮时,将执行类似以下代码的onclick()回调函数:
def onclick():
subprocess.Popen("python main.py")
但是,日志仍然打印在我最初打开的cmd窗口中。这不是我想要的,因为很难区分哪个日志属于哪个“ main.py”。 有什么解决办法吗?
答案 0 :(得分:1)
防止控制台中子进程输出有两种选择,第一种是使用子进程。只有当使用子进程的通信方法完成子进程的处理后,PIPE才能将数据从子进程发送到缓冲区并读取ut:>
def onclick():
subprocess.Popen("python main.py", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
如果在母进程中根本不需要子进程的输出,请使用subprocess.DEVNULL:
def onclick():
subprocess.Popen("python main.py", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
编辑:
如果您根本不希望主进程拥有子进程的输出,或者如果输出太大而PIPE可能会崩溃。您最好使用DEVNULL和日志记录模块:
#In child process setup logging
logging.basicConfig(
filename="logfile", format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
#then in child process substitute all print to logging.info, logging.warning, #logging.error and whatewer you want.
# Then start child process the following way from master process:
def onclick():
subprocess.Popen("python main.py", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
我希望答案对您有用,随时问问题。