Python脚本转.exe后运行异常求助:VS Code正常,打包后出Traceback错误
Python脚本打包为.exe后无法正常运行的解决方案求助
将Python脚本通过PyInstaller打包成.exe后,程序运行时出现Traceback错误,无法像在VS Code中那样正常执行。已尝试使用py -m PyInstaller --onefile -w 脚本名.py重新打包,但问题仍未解决。
我的代码如下:
from time import sleep from newspaper import Article, Config import nltk from newspaper.article import ArticleException, ArticleDownloadState def get_News(): while True: print ("Enter URL: ") url = input('') print("\n") user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) Gecko/20100101 Firefox/78.0' config = Config() config.browser_user_agent = user_agent config.request_timeout = 10 article = Article(url, config=config, lang='en') slept = 0 article.download() article.parse() title = article.title author = article.authors pub_date = article.publish_date text = article.text article.nlp() print('Display Title, Author and Publish Date:') print(title ,author, pub_date) print ('\n' +'Display Text from Article: ' + '\n' + text) print ('\n' + 'Display Article Summary: ') print(article.summary) print('\n') print('Display Keywords: ') print(article.keywords) if url == '': print('No URL Found. Exiting the Program...') break if __name__ == '__main__': get_News()
最初使用的打包命令:py -m PyInstaller --onefile 脚本名.py,恳请提供可行的解决方案。
解决方案
1. 补充nltk语料库资源
newspaper依赖nltk的语料库,PyInstaller不会自动打包这些资源,需手动添加:
- 先在VS Code中运行
nltk.download(),下载所有必要语料(比如punkt、averaged_perceptron_tagger),找到nltk数据存储路径(Windows一般是C:\Users\你的用户名\AppData\Roaming\nltk_data)。 - 打包时用
--add-data参数引入该目录:
(Linux/macOS用冒号分隔路径:py -m PyInstaller --onefile --add-data "C:\Users\你的用户名\AppData\Roaming\nltk_data;nltk_data" 脚本名.py--add-data "/Users/你的用户名/nltk_data:nltk_data")
2. 手动添加newspaper的隐藏导入
PyInstaller可能漏检newspaper的部分子模块,需指定隐藏导入:
- 直接在打包命令中添加
--hidden-import参数:
或者创建py -m PyInstaller --onefile --add-data "nltk_data路径;nltk_data" --hidden-import newspaper --hidden-import newspaper.article --hidden-import newspaper.config 脚本名.pyhook-newspaper.py文件(内容如下),放在PyInstaller hooks目录或用--additional-hooks-dir指定路径:from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('newspaper')
3. 移除-w参数
你的脚本需要接收用户输入,-w参数会隐藏控制台窗口,导致无法输入而报错,打包时去掉该参数:
py -m PyInstaller --onefile --add-data "nltk_data路径;nltk_data" --hidden-import newspaper 脚本名.py
4. 排查剩余错误
打包完成后,双击dist目录下的.exe,查看控制台输出的具体错误,根据提示补充缺失的依赖或资源。
内容的提问来源于stack exchange,提问作者Aiko
相关产品推荐
相关产品推荐

