[Python] pipreqs fails with SyntaxError when scanning Python 2 code in a Python 3 environment

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I have a python3 virtual environment but there are some python2 syntaxed files. I am trying to get the requirement.txt using pip freeze and pipreqs, but neither worked.

    The error message looks like follow:

    INFO: Not scanning for jupyter notebooks.
    ERROR: Failed on file: ./tests/data/python2.py
    Traceback (most recent call last):
    File "<frozen runpy>", line 198, in _run_module_as_main
    File "<frozen runpy>", line 88, in _run_code
    File "/Users/plus1/Desktop/black/venv/lib/python3.12/site-packages/pipreqs/pipreqs.py", line 615, in <module>
    main() # pragma: no cover
    ^^^^^^
    File "/Users/plus1/Desktop/black/venv/lib/python3.12/site-packages/pipreqs/pipreqs.py", line 609, in main
    init(args)
    File "/Users/plus1/Desktop/black/venv/lib/python3.12/site-packages/pipreqs/pipreqs.py", line 533, in init
    candidates = get_all_imports(
    ^^^^^^^^^^^^^^^^
    File "/Users/plus1/Desktop/black/venv/lib/python3.12/site-packages/pipreqs/pipreqs.py", line 153, in get_all_imports
    raise exc
    File "/Users/plus1/Desktop/black/venv/lib/python3.12/site-packages/pipreqs/pipreqs.py", line 139, in get_all_imports
    tree = ast.parse(contents)
    ^^^^^^^^^^^^^^^^^^^
    File "/opt/homebrew/Cellar/python@3.12/3.12.2_1/Frameworks/Python.framework/Versions/3.12/lib/python3.12/ast.py", line 52, in parse
    return compile(source, filename, mode, flags,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "<unknown>", line 7
    print >> sys.stderr , "Look, a repr:", `sys`
    ^
    SyntaxError: invalid syntax


    And the erroring file looks like below:

    #!/usr/bin/env python2

    import sys

    print >> sys.stderr , "Warning:" ,
    print >> sys.stderr , "this is a blast from the past."
    print >> sys.stderr , "Look, a repr:", `sys`


    def function((_globals, _locals)):
    exec ur"print 'hi from exec!'" in _globals, _locals

    Continue reading...

Compartilhe esta Página