运行 在外部 gnome 终端中使用 subprocess.Popen 命令

running commands in an external gnome-terminal using subprocess.Popen

我正在尝试在我生成的终端中使用通信来执行命令。

 sitecreate_proc = subprocess.Popen(['gnome-terminal'], stdout=subprocess.PIPE, stdin=subprocess)
 out = sitecreate_proc.communicate("pwd")
 print out

"out" 变量始终为空。 需要显示终端。

gnome-terminal 是一个图形应用程序,作为一个应用程序,likely doesn't use its own standard streams that it got from the parent process.

您需要 运行 控制应用程序而不是与它们通信 -

  • 命令本身:

    >>> subprocess.check_output("pwd")
    '/c/Users/Ivan\n'
    
  • 交互式shell命令,然后向其发送输入并根据Interacting with bash from python

    接收响应

如果您只需要将流数据输出到 python 正在使用的同一控制台,您可以在获取数据时简单地写出它们的数据 - automatically with tee,或手动在适当的时候。


相反,如果您需要在桌面上启动一个独立的终端仿真器 window 并通过 IPC 与之交互,那完全是另一回事 - 即 UI automation,与此无关使用标准控制台流。

The most common way for that in Linux is D-Bus (there are other options outlined on the previous link). Ppl report however (as of 2012) that gnome-terminal doesn't support D-bus and you have to jump through hoops to interact with it. There is an article on controlling konsole via D-Bus 不过

我记得交流 return 一个元组,

communicate() returns a tuple (stdoutdata, stderrdata)

。所以你不能用户交流("pwd")。 gnome-terminal returns,然后尝试通过 sitecreate_proc.communicate()[0] for stroutdate 或 sitecreate_proc.communicate()[0] for stderrdata

获得该结果