python - 以编程方式生成 requirements.txt 文件

标签 python subprocess pip requirements.txt

我正在尝试以编程方式生成 requirements.txt 文件。这样我就可以将它与第二个 .txt 文件进行比较。到目前为止,我已经尝试了以下方法,但它们只将要求输出到控制台(没有生成 .txt 文件)。

到目前为止我已经尝试过

    import pip

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

    from subprocess import call

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

如果我尝试在终端中手动运行相同的命令,则生成的文件没有问题。有什么建议吗?

最佳答案

要求pip直接提供分布列表

脚本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")

然后您会在 requirements.txt 文件中获得预期的内容。

关于python - 以编程方式生成 requirements.txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24321933/

相关文章:

python - 如何在 Keras 中正确实现自定义事件正则化器?

python - Pyinstaller 错误 xfd 模块

python - Pip 安装在 Virtualenv 中工作,但*不*与 `-r requirements.txt` 一起工作

python - OpenCV Python dlib 构建轮 (setup.py)

python - Numpy:逐行减去 2 个 numpy 数组

python - 如何在 Tkinter 中制作颜色选择比例尺?

javascript - 如何通过 Python 使用 GhostDriver 处理警报?

python - 使用环境变量在python中调用子进程

python - 找不到文件错误 : [WinError 2] The system can't find the specified file

python - 如何获取生成的子进程命令字符串