Python 3.x 如何获得python变量的终端输出-用于规范化应用程序

Python 3.x 如何获得python变量的终端输出-用于规范化应用程序,python-3.x,ubuntu-12.10,canonical-quickly,Python 3.x,Ubuntu 12.10,Canonical Quickly,我正在使用Ubuntu12.10快速创建一个Ubuntu应用程序。它是一个用于启动、停止和重新启动Apache2 web服务器的简单GUI 首先让我谈谈我面临的问题所在的代码部分: # handler for restart apache button def on_button_restart_clicked(self, button): self.label = self.builder.get_object("labelStatus")

我正在使用Ubuntu12.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 在终端中,此时的输出是-*重新启动web服务器apache2[OK]。。。等待并在重新启动apache后立即显示下一行-Web服务器apache2已重新启动

我如何解决这些问题-

  • 我不想在标签文本中硬编码消息。那么,如何跟踪终端输出并将其捕获到python变量中,以便设置标签文本呢
  • 由于我正在使用gksudo,弹出窗口将输入密码,但问题是它正在显示命令。如何在python中优雅地使用sudo
  • 我对python完全陌生。
    提前感谢

    对堆栈的快速检查将我带到了这个链接;希望能有帮助

    我还发现了:

    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()