Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the requirements of a Python single script

I would like to know how to extract the requirements from a single python script. I tried the following way, at the beginning of my file, immediately after the imports:

try:
    from pip._internal.operations import freeze
except ImportError:  # pip < 10.0
    from pip.operations import freeze

x = freeze.freeze()
for p in x:
    print(p)

The piece of code above, however, gives me back all the Python frameworks installed locally. I would like to extract only the necessary requirements for the script, in order to be able to deploying the final application.
I hope I was clear.

like image 743
Memmo Avatar asked Feb 13 '19 13:02

Memmo


People also ask

How does requirements file work in Python?

A requirements file is a list of all of a project's dependencies. This includes the dependencies needed by the dependencies. It also contains the specific version of each dependency, specified with a double equals sign ( == ). pip freeze will list the current projects dependencies to stdout .


2 Answers

pipreqs is simple to use

install:

pip install pipreqs

in linux in the same folder of your script use:

pipreqs .

then the requirements.txt file is created

pip home page:

https://pypi.org/project/pipreqs/

like image 132
Jose R. Zapata Avatar answered Sep 17 '22 19:09

Jose R. Zapata


You can do this easily with 'modulefinder' python module.

I think you want to print all the modules required by a script. So, you can refer to

http://blog.rtwilson.com/how-to-find-out-what-modules-a-python-script-requires/

or for your ease the code is here:


from modulefinder import ModuleFinder
f = ModuleFinder()
# Run the main script
f.run_script('run.py')
# Get names of all the imported modules
names = list(f.modules.keys())
# Get a sorted list of the root modules imported
basemods = sorted(set([name.split('.')[0] for name in names]))
# Print it nicely
print ("\n".join(basemods))

like image 21
Kumar Saptam Avatar answered Sep 19 '22 19:09

Kumar Saptam