Home > Mobile >  Use subprocess to open terminal and run a command
Use subprocess to open terminal and run a command

Time:02-27

I want to open a new terminal window and run a simple command such as echo hello world or python myscript.py. However all I have achieved is opening a new terminal in which none of my commands are run. Below are some examples of things I have tried:

import subprocess
# -----------------------  
subprocess.Popen(["gnome-terminal", "echo 'Hello World'"])
# -----------------------  
subprocess.Popen(["gnome-terminal", "echo", "Hello", "World"])
# -----------------------  
x = subprocess.Popen(["gnome-terminal"])
x.communicate(["echo hello world"])
# -----------------------  
from subprocess import Popen,PIPE
x = subprocess.Popen(['gnome-terminal'], stdin=PIPE)
x.communicate("echo hello world")
# -----------------------  
def subprocess_cmd(cmd1,cmd2): # adapted from another Stack question
    p1 = Popen(cmd1.split(),stdout=PIPE)
    p2 = Popen(cmd2.split(),stdin=p1.stdout,stdout=PIPE)
    p1.stdout.close()
    return p2.communicate()[0]
subprocess_cmd('gnome-terminal','echo hello world') # Prnts in my IDE and opens blank gnome terminal
# -----------------------  
subprocess.Popen(["gnome-terminal", "echo hello world"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

Where am I going wrong?

CodePudding user response:

Try this:

command = '<my command>'
subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', command], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

Here's the manual page. See also.

  • Related