使用Python,我想在新的终端窗口中启动一个进程,因为这样可以向用户显示正在发生的事情,因为涉及多个进程。
我尝试过:
>>> import subprocess
>>> subprocess.Popen(['gnome-terminal'])
<subprocess.Popen object at 0xb76a49ac>
这可以按照我的意愿工作,打开一个新窗口。
但是如何将参数传递给它呢?就像,当终端启动时,我希望它说,运行ls
。但是这个:
>>> subprocess.Popen(['gnome-terminal', 'ls'])
<subprocess.Popen object at 0xb76a706c>
这又有效,但ls
命令不起作用:空白终端窗口启动。
所以我的问题是,如何使用指定的命令启动终端窗口,以便在窗口打开时运行该命令。
PS:我的目标是仅 Linux。
答案 0 :(得分:5)
$ gnome-terminal --help-all
...
-e, --command Execute the argument to this option inside the terminal
...
如果您希望窗口保持打开,那么您将需要运行一个shell或命令,以便在之后保持打开状态。
答案 1 :(得分:5)
In [5]: import subprocess
In [6]: import shlex
In [7]: subprocess.Popen(shlex.split('gnome-terminal -x bash -c "ls; read -n1"'))
Out[7]: <subprocess.Popen object at 0x9480a2c>
答案 2 :(得分:0)
这是我用来从WINE中的记事本++启动gnome-terminal的系统,
1:notepad ++命令启动
#!/usr/bin/python
#this program takes three inputs:::
#$1 is the directory to change to (in case we have path sensitive programs)
#$2 is the linux program to run
#$3+ is the command line arguments to pass the program
#
#after changing directory, it launches a gnome terminal for the new spawned linux program
#so that your windows program does not eat all the stdin and stdout (grr notepad++)
import sys
import os
import subprocess as sp
dir = sys.argv[1]
dir = sp.Popen(['winepath','-u',dir], stdin=sp.PIPE, stdout=sp.PIPE).stdout.read()[:-1]
os.chdir(os.path.normpath(os.path.realpath(dir)))
print os.getcwd()
print "running '%s'"%sys.argv[2]
cmd=['gnome-terminal','-x','run_linux_program_sub']
for arg in sys.argv[2:]:
cmd.append(os.path.normpath(os.path.realpath(sp.Popen(['winepath','-u',arg], stdin=sp.PIPE, stdout=sp.PIPE).stdout.read()[:-1])))
print cmd
p = sp.Popen(cmd, stdin=sp.PIPE, stdout=sp.PIPE)
2:运行子脚本,我用程序退出后运行bash(在这种情况下通常是python)
#!/bin/sh
#$1 is program to run, $2 is argument to pass
#afterwards, run bash giving me time to read terminal, or do other things
$1 "$2"
echo "-----------------------------------------------"
bash