【问题标题】:running commands in an external gnome-terminal using subprocess.Popen使用 subprocess.Popen 在外部 gnome 终端中运行命令
【发布时间】:2017-09-04 02:11:02
【问题描述】:

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

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

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

【问题讨论】:

  • 我记得通信返回一个元组,communicate() returns a tuple (stdoutdata, stderrdata). so you can't user communicate("pwd"). gnome-terminal returns, then try to get that result, by sitecreate_proc.communicate()[0]` 用于 stroutdate,或sitecreate_proc.communicate()[0] 用于 stderrdata
  • @darvark,是的,你是对的。即使我使用communicate("pwd")[0] 它什么也没给我。
  • @darvark,是的,请发布答案:)

标签: python subprocess popen


【解决方案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

【讨论】:

  • 我的项目需要显示终端。这就是为什么我没有直接运行命令的原因。很抱歉造成误会。
【解决方案2】:

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

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

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

【讨论】:

  • 我无法理解你想说的话(对不起)。你能发布一个代码示例吗?
  • sitecreate_proc = subprocess.Popen(['gnome-terminal'], stdout=subprocess.PIPE) out = sitecreate_proc.communicate()[0] 不会像 ivan_pozdeev 所写的那样返回任何内容。最终您可以尝试获取 bash 退出状态$?,如果它等于 0 则成功,否则为错误。更多详情stackoverflow.com/questions/5631624/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2014-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
相关资源
最近更新 更多