覃天琛
覃天琛

Reputation: 51

How can I open a cmd window everytime I run a python script?

Now I have two python script "GUI.py" and "main.py". The "GUI.py" is written using pyQt5. First, I open a cmd window and run the "python GUI.py" .It opens a window which contains a button named "connect". Everytime I click the button, the onclick() callback function like the following codes will be executed:

def onclick():
    subprocess.Popen("python main.py")

However, the log is still printed in the cmd window I originally opened.That's not what I want because it is hard to tell which log belong to which "main.py". Is there any solution?

Upvotes: 0

Views: 224

Answers (1)

Artiom  Kozyrev
Artiom Kozyrev

Reputation: 3846

You have two choices to prevent output of child process in console the first one is to use subprocess.PIPE to send data from child process to buffer and read ut only when the child process is finiched using communicate method of subprocess:

def onclick():
    subprocess.Popen("python main.py", stdout=subprocess.PIPE, stderr=subprocess.PIPE)

If you do not need output of child process in mother process at all, go with subprocess.DEVNULL:

def onclick():
    subprocess.Popen("python main.py", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

Edit:

If you do not want to have output of child process at master process at all or if output is too big and PIPE could actually crush. You better go with DEVNULL and logging module:

#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)

I hope the answer was useful for you, feel free to ask questions.

Upvotes: 1

Related Questions