bash 有没有办法从bash运行zip文件中的python脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3760970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:39:39  来源:igfitidea点击:

Is there a way to run a python script that is inside a zip file from bash?

pythonmacosbashzippython-module

提问by ForceMagic

I know there is a way to import modules which are in a zip file with python. I created kind of custom python package library in a zip file.

我知道有一种方法可以使用 python 导入 zip 文件中的模块。我在 zip 文件中创建了一种自定义 python 包库。

I would like to put as well my "task" script in this package, those are using the library. Then, with bash, I would like to call the desired script in the zip file without extracting the zip.

我想把我的“任务”脚本也放在这个包中,那些正在使用库。然后,使用 bash,我想在不解压 zip 的情况下调用 zip 文件中所需的脚本。

The goal is to have only one zip to move in a specified folder when I want to run my scripts.

目标是当我想运行我的脚本时,只有一个 zip 可以在指定的文件夹中移动。

回答by ForceMagic

I finally found a way to do this. If I create a zip file, I must create __main__.pyat the root of the zip. Thus, it is possible to launch the script inside the main and call if from bash with the following command :

我终于找到了一种方法来做到这一点。如果我创建一个 zip 文件,我必须__main__.py在 zip 的根目录下创建。因此,可以在 main 中启动脚本并使用以下命令从 bash 调用:

python myArchive.zip

python myArchive.zip

This command will run the __main__.pyfile! :)

此命令将运行该__main__.py文件!:)

Then I can create .commandfile to launch the script with proper parameters.

然后我可以创建.command文件以使用适当的参数启动脚本。

You can also put some code in the __main__.pyfile to give you more flexibility if you need to pass arguments for example.

__main__.py例如,如果您需要传递参数,您还可以在文件中放置一些代码以提供更大的灵活性。

ex: python __main__.py buildProject

前任: python __main__.py buildProject

The reference documentation is here: https://docs.python.org/2/library/runpy.html

参考文档在这里:https: //docs.python.org/2/library/runpy.html

回答by Rod

Have a look at zipimport. It should work directly from the install. You might have to do some work to make the pythonpath point to your zip file/directory.

看看zipimport。它应该直接从安装中工作。您可能需要做一些工作才能使 pythonpath 指向您的 zip 文件/目录。

This module adds the ability to import Python modules (*.py, *.py[co]) and packages from ZIP-format archives. It is usually not needed to use the zipimport module explicitly; it is automatically used by the built-in import mechanism for sys.path items that are paths to ZIP archives.that are paths to ZIP archives.

此模块添加了从 ZIP 格式存档导入 Python 模块(*.py、*.py[co])和包的功能。通常不需要显式使用 zipimport 模块;它由内置导入机制自动用于 sys.path 项目,这些项目是 ZIP 档案的路径。ZIP 档案的路径。