在调用 'os.system()' 之前只运行一些语句

Runs only some statements before 'os.system()' is called

我正在编写一个 Python 程序,该程序具有使用 PyQt5 的 GUI,并且还使用 os.system() 调用 MATLAB 文件。但是,我决定在调用 os.system 之前不执行任何与 PyQt 相关的语句的函数之一。 os.system 之前的 'print' 运行 之类的正常函数,但其​​他函数不会。但是,它 运行 在 os.system 被调用之后就可以了

例如)

def button_clicked(self):
    print("Button Clicked")    #works
    self.label.hide()          #does nothing

    os.system()                #MATLAB called. works

    self.label.hide()          #now works

我完全不知道为什么会这样。真正奇怪的是,该程序似乎忽略了 os.system 之前函数中与 PyQt 相关的所有内容,因为即使我执行以下操作:

def myFunction(self):
    self.label.hide()
    self.label2.hide()
    print("myFunction Called")  

def button_clicked(self):
    self.label.hide()          #does nothing
    self.label2.hide()         #does nothing
    print("Button Clicked")    #works
    self.myFunction()          #does everything in the function unless it's PyQt-related, in this instance, it prints "myFunction Called" and nothing else

    os.system()                #MATLAB called. Works

    self.label.hide()         #now works
    self.label2.hide()        #now works

是不是os.system总是在函数中先执行?但这并不能解释为什么像 'print' 这样的东西会起作用。

os.system() 阻塞。这意味着它不会 return 直到它实际调用的命令 returns(例如:程序退出)。

对于像 Qt 这样的事件驱动系统,这是一个 可怕的 错误,因为阻塞函数阻止事件循环处理 所有事件 :不仅是那些来自系统的事件(例如键盘或鼠标交互),还有它自己的事件,最重要的是绘制的小部件。

您的标签实际上隐藏在 Qt 的角度(您可以尝试 print(self.label.isVisible())),但由于您在那之后立即调用 os.system,Qt 没有时间视觉更新 小部件以反映这一点。

虽然通常线程(使用 python 自己的模块或 Qt 的 QThread,取决于要求,甚至 QRunnable)是潜在阻塞操作的首选,因为您实际上想要启动一个新程序, 最简单的解决方案是使用 QProcess, 也许用它自己的静态方法 startDetached().