user13005310
user13005310

Reputation:

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. From what I've been reading online, the best way to do this is to use the Python library subprocess. 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.

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!

Upvotes: 1

Views: 1681

Answers (1)

tomgalpin
tomgalpin

Reputation: 2093

You are chaining commands to run in the local shell using

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

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

Upvotes: 3

Related Questions