使用subprocess.Popen在外部gnome-terminal中运行命令

时间:2017-04-08 19:17:26

标签: python subprocess popen

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

 sitecreate_proc = subprocess.Popen(['gnome-terminal'], stdout=subprocess.PIPE, stdin=subprocess)
 out = sitecreate_proc.communicate("pwd")
 print out
" out"变量总是空的。 显示终端是必要的。

2 个答案:

答案 0 :(得分:1)

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或手动在适当的时候。

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

The most common way for that in Linux is D-Bus(上一个链接中列出了其他选项)。然而,Ppl报告(截至2012年)that gnome-terminal doesn't support D-bus and you have to jump through hoops to interact with it。但是有an article on controlling konsole via D-Bus

答案 1 :(得分:0)

我记得沟通返回一个元组,

  

communic()返回一个元组(stdoutdata,stderrdata)

。所以你不能用户沟通(“pwd”)。 gnome-terminal返回,然后尝试获取结果,sitecreate_proc.communicate()[0]为stroutdate,或sitecreate_proc.communicate()[0]为stderrdata

相关问题