Retrieving the requirements of a Python single script

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))


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/