Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all python packages used by a script in python3

There's a few of these question I've read through, but they all seem to link to methods exclusively for python 2.x and I'm working in python 3.x.

I have a python file, call it test.py, it has a number of package imports (eg. import numpy as np) but it also imports some other files, lets call them subTest1.py and subTest2.py. Each of the subTest files have their own imports (possibly both other files and packages). Is there an automated way to get a list of all packages required to run the route script (test.py)?

I'm aware that pip freeze shows me every packages installed, but that's not what I'm looking for - there could be a package installed that isn't required to run the test.py script.

Questions that are similar but python 2.x:

Return a list of imported Python modules used in a script?

Get all modules/packages used by a python project

Packages that seem to be specific to python 2.x:

snakefood

pipreqs

Where pipreqs fails:

Traceback (most recent call last):
  File "c:\anaconda36\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\anaconda36\envs\tensorflow\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Anaconda36\envs\tensorflow\Scripts\pipreqs.exe\__main__.py", line 9, in <module>
  File "c:\anaconda36\envs\tensorflow\lib\site-packages\pipreqs\pipreqs.py", line 396, in main
    init(args)
  File "c:\anaconda36\envs\tensorflow\lib\site-packages\pipreqs\pipreqs.py", line 341, in init
    extra_ignore_dirs=extra_ignore_dirs)
  File "c:\anaconda36\envs\tensorflow\lib\site-packages\pipreqs\pipreqs.py", line 91, in get_all_imports
    raise exc
  File "c:\anaconda36\envs\tensorflow\lib\site-packages\pipreqs\pipreqs.py", line 77, in get_all_imports
    tree = ast.parse(contents)
  File "c:\anaconda36\envs\tensorflow\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 49
    print vsize
              ^
SyntaxError: Missing parentheses in call to 'print'
like image 546
user6916458 Avatar asked Mar 24 '26 06:03

user6916458


1 Answers

You can use pipreqs package. (Docs)

To Install:

pip3 install pipreqs

Usage:

pipreqs ./your_script_directory

It produces a requirements.txt file in your script directory with all the dependencies used.

like image 160
Rithin Chalumuri Avatar answered Mar 25 '26 21:03

Rithin Chalumuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!