使用参数启动gnome-terminal

6 投票
3 回答
10076 浏览
提问于 2025-04-16 09:37

我想用Python在一个新的终端窗口中启动一个进程,这样可以让用户看到发生了什么,因为涉及到多个进程。

我试着这样做:

>>> import subprocess
>>> subprocess.Popen(['gnome-terminal'])
<subprocess.Popen object at 0xb76a49ac>

这样做是有效的,确实打开了一个新窗口。

但是我该怎么传递参数呢?比如,当终端启动时,我想让它执行ls命令。但这样做:

>>> subprocess.Popen(['gnome-terminal', 'ls'])
<subprocess.Popen object at 0xb76a706c>

虽然这样也能工作,但ls命令没有执行:打开的是一个空白的终端窗口。

所以我的问题是,如何在打开终端窗口时指定一个命令,让这个命令在窗口打开时就执行。

附注:我只针对Linux系统。

3 个回答

0

这是我用来在WINE中从Notepad++启动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
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>
6
$ gnome-terminal --help-all

 ...

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

 ...

如果你想让这个窗口保持打开,那么你需要运行一个可以让它保持打开状态的命令或者程序。

撰写回答