【问题标题】:How to get the terminal output to python variable - for canonical quickly application如何将终端输出获取到 python 变量 - 用于规范的快速应用程序
【发布时间】:2013-10-31 18:52:17
【问题描述】:

我正在 ubuntu 12.10 上快速创建一个 Ubuntu 应用程序。它是一个用于启动、停止和重新启动 Apache2 Web 服务器的简单 GUI。

让我先给出我遇到问题的代码部分 -

    # handler for restart apache button    
    def on_button_restart_clicked(self, button):
        self.label = self.builder.get_object("labelStatus")
        self.label.set_text("Restarting web server apache2")
        os.system("gksudo /etc/init.d/apache2 restart")
        self.label.set_text("Web server apache2 Restarted")

单击按钮后,将调用该方法但未显示标签 - 重新启动 Web 服务器 apache2 此时在终端中的输出是 - * Restarting web server apache2 [ OK ] ... waiting 并且一旦重新启动 apache 就会显示下一行 - Web server apache2 重启

我该如何解决这些问题 -

  1. 我不想在标签文本中对消息进行硬编码。那么如何跟踪终端输出并将其捕获到 python 变量中,以便我可以设置标签文本。
  2. 因为我使用的是 gksudo,所以弹出窗口来输入密码,但问题是它正在显示命令。如何在 python 中优雅地使用 sudo?

我对 python 完全陌生。 提前致谢

【问题讨论】:

    标签: python-3.x ubuntu-12.10 canonical-quickly


    【解决方案1】:

    快速检查堆栈将我带到此链接;希望对你有帮助

    Pipe subprocess standard output to a variable

    我也发现了这个:

    from StringIO import StringIO 
    import sys
    
    # store a reference to the old
    old_stdout = sys.stdout
    
    # var to store everything that is sent to the std out
    result = StringIO()
    sys.stdout = result
    
    # your function here; all results should be stored
    user_def_function()
    
    # reset the std out
    sys.stdout = old_stdout
    
    # result to string
    result_string = result.getvalue()
    

    【讨论】:

      猜你喜欢
      • 2015-06-13
      • 2020-06-04
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      相关资源
      最近更新 更多