user6039682
user6039682

Reputation:

Running a secondary script in a new terminal

When running a secondary python script:

An example, two subprocesses to be run, first.py should be called first, only then the second is called, second.py. Because the two scripts first.py and second.py are interdependent (as in first.py goes to wait mode, until second.py is run, then first.py resumes, and I don't know how to make this communication work between them in terms of subprocesses.)

import subprocess

command = ["python", "first.py"]
command2 = ["python", "second.py"]
n = 5
for i in range(n):
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    p2 = subprocess.Popen(command2, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
        output = p.stdout.readline().strip()
        print output
        if output == 'stop':
            print 'success'
            p.terminate()
            p2.terminate()
            break

Framework (Ubuntu, python 2.7)

Upvotes: 3

Views: 1751

Answers (3)

tripleee
tripleee

Reputation: 189447

I guess you want something like

subprocess.call(['xterm','-e','python',script])

Good old xterm has almost no frills; on a Freedesktop system, maybe run xdg-terminal instead. On Debian, try x-terminal-emulator.

However, making your program require X11 is in most cases a mistake. A better solution is to run the subprocesses with output to a log file (or a socket, or whatever) and then separately run tail -f on those files (in a different terminal, or from a different server over ssh, or with output to a logger which supports rsyslog, or or or ...) which keeps your program simple and modular, free from "convenience" dependencies.

Upvotes: 2

fredrik
fredrik

Reputation: 10281

You can specify the tty of the terminal window you wish the command to be carried out in:

ls > /dev/ttys004

However, I would recommend going for the tmux approach for greater control (see my other answer).

Upvotes: 1

fredrik
fredrik

Reputation: 10281

If you're using tmux, you can specify which target you want the command to run in:

tmux send -t foo.0 ls ENTER

So, if you've created a tmux session foo.0, you should be able to do:

my_command = 'ls'
tmux_cmd = ['tmux', 'send', '-t', 'foo.0', my_command]
p = subprocess.Popen(tmux_cmd)

Upvotes: 2

Related Questions