使用在外部gnometerminal中运行命令子流程.Popen

2024-10-03 13:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在我生成的终端中使用communication执行命令。在

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

“out”变量始终为空。 显示终端是必要的。在


Tags: 终端stdinstdoutpwdprocout执行命令terminal
2条回答

当我记得通信返回元组时

communicate() returns a tuple (stdoutdata, stderrdata)

一。所以你不能和用户交流(“pwd”)。gnome终端返回,然后尝试通过sitecreate_proc.communicate()[0]返回stroutdate,或sitecreate_proc.communicate()[0]来获取结果

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 ^{},或者在适当的时候手工编写。在


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

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

相关问题 更多 >