Crash when calling Python script with exec() from QMenuBar
-
I am writing my first application using PyQt5 and I have come across some unexpected behaviour.
The PyQt5 version is 5.15.6 and I am running Python 3.9.10 in PyCharm on Windows 11.The 3 scripts show what is happening.
- Running "number_list.py" directly is good.
- Running "test1.py" does what I would expect and runs "number_list.py"
- Running "test2.py" and selecting 'File/Show Number List' will open "number_list.py" but then crashes.
number_list.py
from PyQt5.QtWidgets import \ QWidget, \ QApplication, \ QListView, \ QHBoxLayout from PyQt5.QtGui import \ QStandardItem, \ QStandardItemModel import sys class window(QWidget): def __init__(self): super().__init__() numList = QListView() model = QStandardItemModel() numList.setModel(model) for x in range(10): model.appendRow(QStandardItem(str(x))) layout = QHBoxLayout(self) layout.addWidget(numList) self.show() if __name__ == '__main__': print('Hello World!') app = QApplication(sys.argv) win = window() sys.exit(app.exec_())
if __name__ == '__main__': exec(open('<path>/number_list.py').read())
from PyQt5.QtWidgets import \ QWidget, \ QMainWindow, \ QApplication, \ QAction, \ QListView, \ QHBoxLayout from PyQt5.QtGui import \ QStandardItem, \ QStandardItemModel import sys class window(QMainWindow): def __init__(self): super().__init__() menu = self.menuBar() fileMenu = menu.addMenu('&File') showList = QAction('&Show Number List', self) showList.triggered.connect(self.run_test2) fileMenu.addAction(showList) self.show() def run_test2(self): exec(open('<path>/number_list.py').read()) if __name__ == '__main__': app = QApplication(sys.argv) win = window() sys.exit(app.exec_())
The debugger in PyCharm doesn't seem to be any help.
Console Tab
Connected to pydev debugger (build 213.7172.26) Hello World! Process finished with exit code -1073741819 (0xC0000005)
And the Debugger Tab has no traceback, only "Frames are not available".
Any comments or fixes would be greatly appreciated.
-
That's not what
exec
is designed for.
If you want to run other python scripts (or scripts in general) use https://docs.python.org/3/library/subprocess.html but in your case, it might be worth for you just toimport
the class you want to use from the other file, and thenshow
it on the main python file, for example:from number_list import window
from yourtest1.py
file, and then using what you have inside theif __name__ == "__main__"
but fromtest1.py
. -
@CristianMaureira Thanks for your reply and for pointing me in the right direction.
My searches all came up with exec as the way to do this and it seems to work most of the time.
subprocess is working now.