Python3使用exec执行外部py文件触发RuntimeError错误如何解决
问题原因
该报错是Thonny IDE内置运行环境和exec()执行外部脚本时的上下文、标准输入交互逻辑冲突导致的,同时exec()直接读取文件内容执行本身属于非规范的外部脚本调用方式,极易出现路径、作用域、运行环境冲突问题。
解决方案
下面按优先级给出可行修复方案:
方案1:用subprocess启动独立进程运行外部脚本(最稳妥,无上下文冲突)
替换原有exec()写法,用subprocess启动独立Python进程执行usersend.py,修改后的代码如下:from tkinter import * import subprocess import os def send(): # 拼接脚本绝对路径,避免相对路径找不到文件 current_path = os.path.dirname(os.path.abspath(__file__)) target_script = os.path.join(current_path, 'usersend.py') # 启动独立进程运行脚本,树莓派环境可加lxterminal弹出独立终端执行 subprocess.Popen(['python3', target_script]) # 如果usersend.py需要交互输入,用下面的写法弹出终端运行 # subprocess.Popen(['lxterminal', '-e', 'python3', target_script]) with open("User_Data.txt") as f: lines = f.read() ##Assume the sample file has 3 lines second = lines.split()[2] root = Tk() label = Label(root, text='Welcome, ' + second + ' to Jammer!') label.config(font=('Courier', 44)) label.pack() button = Button(root, text='Send a game', command = send) button.config(font=('Courier', 10)) button.pack(side = 'bottom', expand = False, padx = 4, pady = 4) root.mainloop()注:如果你原代码漏了
root.mainloop()要补上,否则Tkinter窗口无法正常运行。方案2:封装外部脚本逻辑为函数导入调用(性能最优)
把usersend.py里的所有执行逻辑封装到main函数中,示例如下:# usersend.py 代码修改示例 def main(): # 把原本usersend.py里直接执行的所有代码放到这个函数里 print("执行usersend逻辑") if __name__ == "__main__": main()然后在当前Tkinter代码中直接导入调用即可,修改send函数:
from usersend import main def send(): main()临时验证方案
你可以直接退出Thonny,在系统终端中进入脚本所在目录,执行python3 User2.py运行原代码,即可避开Thonny运行环境的限制验证代码逻辑是否正常。
内容的提问来源于stack exchange,提问作者RockZombie
相关产品推荐
相关产品推荐

