使用Pyinstaller将Scrapy打包为更大程序的一部分

如何解决使用Pyinstaller将Scrapy打包为更大程序的一部分

我正在尝试使用Pyinstaller将Scrapy打包为更大程序的一部分。
在执行代码形式的源代码时,所有内容均按预期运行,但是从可执行文件运行时,一切将返回:

[scrapy.utils.log] INFO: Scrapy 2.3.0 started (bot: NGL)
[scrapy.utils.log] INFO: Versions: lxml 4.5.1.0,libxml2 2.9.10,cssselect 1.1.0,parsel 1.6.0,w3lib 1.22.0,Twisted 20.3.0,Python 3.8.5 (default,Jul 27 2020,08:42:51) - [GCC 10.1.0],pyOpenSSL 19.1.0 (OpenSSL 1.1.1g  21 Apr 2020),cryptography 3.0,Platform Linux-5.8.3-arch1-1-x86_64-with-glibc2.4
Traceback (most recent call last):
  File "scrapy/spiderloader.py",line 76,in load
KeyError: 'ngl'

During handling of the above exception,another exception occurred:

Traceback (most recent call last):
  File "cli.py",line 9,in <module>
  File "ui.py",line 159,in main
  File "ui.py",line 147,in start
  File "ui.py",line 67,in print
  File "NGL/spiders/NGL.py",line 127,in main
  File "scrapy/crawler.py",line 191,in crawl
  File "scrapy/crawler.py",line 224,in create_crawler
  File "scrapy/crawler.py",line 228,in _create_crawler
  File "scrapy/spiderloader.py",line 78,in load
KeyError: 'Spider not found: ngl'

不幸的是,我不知道如何实际调试pyinstaller软件包:/

这是目录树:

.
├── LICENSE
├── main
│   ├── checkers.py
│   ├── cli.py
│   ├── decorators.py
│   ├── fixers.py
│   ├── licences.py
│   ├── NGL
│   │   ├── __init__.py
│   │   ├── items.py
│   │   ├── middlewares.py
│   │   ├── pipelines.py
│   │   └── spiders
│   │       ├── __init__.py
│   │       └── NGL.py
│   ├── scrapy.cfg
│   ├── terminal_tools.py
│   ├── text_tools.py
│   └── ui.py

NGL 中没有 settings.py ,因为我是在 /main/NGL/spiders/NGL.py 中注入直形蜘蛛>与:

def main(url,save_path):
    folder = save_path
    if os.path.exists(folder):
        shutil.rmtree(folder)
    process = CrawlerProcess(
        settings={
            "LOG_ENABLED": True,"LOG_FORMAT": "[%(name)s] %(levelname)s: %(message)s","LOG_LEVEL": "INGO","BOT_NAME": "NGL","SPIDER_MODULES": ["NGL.spiders"],"NEWSPIDER_MODULE": "NGL.spiders","IMAGES_STORE": folder,"ROBOTSTXT_OBEY": True,"ITEM_PIPELINES": {
                "NGL.pipelines.DownloadPipeline": 300,"NGL.pipelines.CleanerPipeline": 600,},"IMAGES_URLS_FIELD": "Image Url","FEEDS": {
                f"{folder}/data.csv": {
                    "format": "csv","encoding": "utf8","fields": [
                        "Inventory number","Full title","Date made","Artist","Artist dates","Medium and support","Dimensions","Overview","In-Depth","Copywright","Image Url","Artwork Url",],}
            },)
    process.crawl("ngl",start_urls=[url])
    process.start()

以及用于打包的命令:

pyinstaller main/cli.py  --clean --onefile --name NGA_linux -p main:main/NGL:main/NGL/spiders

解决方法


这样可以解决KeyError: 'Spider not found: ngl'错误,但是如果您尝试将已编译的程序包移动到项目文件夹之外的任何地方,就会出现一个新错误:(
一切都按预期开始,但随后又开始了:

Traceback (most recent call last):
  File "scrapy/utils/defer.py",line 55,in mustbe_deferred
  File "scrapy/core/spidermw.py",line 60,in process_spider_input
  File "scrapy/core/scraper.py",line 152,in call_spider
  File "scrapy/utils/misc.py",line 218,in warn_on_generator_with_return_value
  File "scrapy/utils/misc.py",line 203,in is_generator_with_return_value
  File "inspect.py",line 985,in getsource
  File "inspect.py",line 967,in getsourcelines
  File "inspect.py",line 798,in findsource
OSError: could not get source code


我能够缩小问题的范围。 我需要在相同的位置编译包和Spider,并保留这样的dir结构:

.
├── NGA_linux # <-- pyinstaller package
└── NGL
    └── spiders
        └── NGL.py <--spider

使用此工具,一切正常,但是没有人知道如何消除此“额外”文件吗?


在OSX下编译仍然会破坏它
有谁知道如何解决此问题?

我找到了答案!
但是我不太确定如何解决此问题,但确实可以解决
有趣的是,只有有用的信息在某些中文博客文章上,尽管

https://iamting93.github.io/2019/08/31/python/linux%E4%B8%8B%E5%88%A9%E7%94%A8pyinstaller%E6%89%93%E5%8C%85scrapy/(或懂中文的人)
它进一步引用了该帖子:
https://blog.csdn.net/u010600274/article/details/99345367
其中具有 .spec 文件

的良好基础示例 所有要做的-将('.','.')添加到datas=[]
这会将整个项目复制到最终包的根目录。
不是很优雅,但是可以用!
据我了解,Scrapy会动态加载一些文件,如果没有这些文件,最终包装中的数据结构就会非常沮丧。

总结一下

  1. 清理了项目树(尽管不确定是否真的很重要):
.
├── cli.py
├── LICENSE
├── NGL_linux.spec
├── scrapy.cfg
├── main
│   ├── __init__.py
│   ├── checkers.py
│   ├── decorators.py
│   ├── fixers.py
│   ├── licences.py
│   ├── terminal_tools.py
│   ├── text_tools.py
│   └── ui.py
└── NGL
    ├── __init__.py
    ├── items.py
    ├── middlewares.py
    ├── pipelines.py
    └── spiders
        ├── __init__.py
        └── NGL.py
 
  1. 通过以下方式生成NGL_linux.spec
pyi-makespec cli.py --onefile -n NGL_linux -p main:NGL:NGL/spiders --windowed
  1. 在Pyinstaller的 .spec 文件中将datas设置为('.','.')
# NGL_linux.spec
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None


a = Analysis(['cli.py'],pathex=['main','NGL','NGL/spiders',{absolute project path here}],binaries=[],datas=[('.','.')],hiddenimports=[],hookspath=[],runtime_hooks=[],excludes=[],win_no_prefer_redirects=False,win_private_assemblies=False,cipher=block_cipher,noarchive=False)
pyz = PYZ(a.pure,a.zipped_data,cipher=block_cipher)
exe = EXE(pyz,a.scripts,a.binaries,a.zipfiles,a.datas,[],name='NGL_linux',debug=False,bootloader_ignore_signals=False,strip=False,upx=True,upx_exclude=[],runtime_tmpdir=None,console=True )
  1. 运行pyinstaller NGL_linux.spec --clean生成软件包

现在一切正常,没有任何问题!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-