2011-01-08 147 views
3

使用Python,我想在一個新的終端窗口中啓動一個進程,因爲這樣可以向用戶顯示發生了什麼,並且因爲涉及多個進程。使用參數啓動gnome-terminal

我試着這樣做:

>>> 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。

回答

5
$ gnome-terminal --help-all 

... 

    -e, --command     Execute the argument to this option inside the terminal 

... 

如果你想在窗口住宿開放的,那麼你就需要運行保持打開狀態後殼或命令。

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> 
0

這是系統,我使用發動侏儒末端從記事本++在酒,

1:記事本++命令來啓動

#!/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