使用子进程打开终端和 运行 命令
Use subprocess to open terminal and run a command
我想打开一个新终端 window 和 运行 一个简单的命令,例如 echo hello world
或 python myscript.py
。然而,我所做的只是打开一个新终端,其中 none 我的命令是 运行。以下是我尝试过的一些示例:
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)
我哪里错了?
试试这个:
command = '<my command>'
subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', command], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
这是manual page. See also。
我想打开一个新终端 window 和 运行 一个简单的命令,例如 echo hello world
或 python myscript.py
。然而,我所做的只是打开一个新终端,其中 none 我的命令是 运行。以下是我尝试过的一些示例:
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)
我哪里错了?
试试这个:
command = '<my command>'
subprocess.Popen(['gnome-terminal', '--', 'bash', '-c', command], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
这是manual page. See also。