Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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.

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

like image 604
ForceMagic Avatar asked Sep 21 '10 13:09

ForceMagic


People also ask

Can Python read files from ZIP?

Python can work directly with data in ZIP files. You can look at the list of items in the directory and work with the data files themselves.

How do I read a zip folder in Python?

zip" # opening the zip file in READ mode with ZipFile(file_name, 'r') as zip: # printing all the contents of the zip file zip. printdir() # extracting all the files print('Extracting all the files now...') zip. extractall() print('Done! ')


2 Answers

I finally found a way to do this. If I create a zip file, I must create __main__.py at 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 :

python myArchive.zip

This command will run the __main__.py file! :)

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

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

ex: python __main__.py buildProject

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

like image 82
ForceMagic Avatar answered Oct 21 '22 21:10

ForceMagic


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.

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.

like image 20
Rod Avatar answered Oct 21 '22 21:10

Rod