5

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?

K Engle
  • 1,322
  • 2
  • 11
  • 23

3 Answers3

7

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.

Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98
3
subprocess.Popen(['pip', 'freeze'], stdout=open('/tmp/pip.log', 'w'))
Shuo
  • 8,447
  • 4
  • 30
  • 36
1

Using pip for this is strongly discouraged by the developers of pip. It is also broken in more recent versions of pip. Here is a summary of the approach suggested on the linked Github issue. Very similar to the accepted answer but using the pkg_resources module instead.

import pkg_resources


def generate_pip_freeze() -> str:
    requirements = ""
    for dist in pkg_resources.working_set:
        req = dist.as_requirement()
        requirements += f"{req}\n"
    return requirements

or more succintly:

def generate_pip_freeze() -> str:
    return "\n".join(
        str(dist.as_requirement()) for dist in pkg_resources.working_set
    )
GuillemB
  • 540
  • 4
  • 13