Search code examples
pythonsubprocesspiprequirements.txt

Programmatically generate requirements.txt file


I'm trying to generate a requirements.txt file programatically. This way I can diff it against a second .txt file. So far I've tried the following, but they only output the requirements to console (No .txt file is generated).

So far I've tried

    import pip

    pip.main(["freeze",">","requirements.txt"])

and

    from subprocess import call

    call(["pip","freeze", ">","requirements.txt"])

If I attempt to run the same command manually in terminal though, the file is generated without issue. Any suggestions?


Solution

  • Ask pip to directly provide the list of distributions

    Script myfreeze.py

    import pip
    with open("requirements.txt", "w") as f:
        for dist in pip.get_installed_distributions():
            req = dist.as_requirement()
            f.write(str(req) + "\n")
    

    Then you get expected content in your requirements.txt file.