且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Python virtualenv 移动到不同的系统(计算机)并使用 Site-packages 中存在的包

更新时间:2023-10-23 12:05:16

将 virtualenv 从一台计算机移动到另一台计算机,甚至在同一台计算机上从一个位置移动到另一个位置是一个坏主意,并且这就是为什么:

Moving a virtualenv from a computer to another, and even on the same computer from a location to another is a bad idea , and this is why :

  • 由于许多二进制文件和库都是符号链接,并且链接到您的旧系统二进制文件和库,因此在其他机器上无法运行.
  • 由于您的 virtualenv 中的许多 bin/ 脚本依赖于 系统 上的 virtualenv path,它如果您将 virtualenv 移动到另一个位置(即使在同一系统上),也将不起作用.
  • Since a lot of the binaries and libs are symlinks, and linked to your old system binaries and libs, it won't work on other machines.
  • Since many of bin/ scripts in your virtualenv depends on the virtualenv path on the system , it won't work if you moved the virtualenv to another location (even on same system either .)

所以推荐的方式是:

  • 首先生成requirements.txt文件:

  • First generate requirements.txt file :

 pip freeze > requirements.txt

  • 在移动所有内容(virtualenv 目录除外)后,创建一个新的 virtualenv,激活它并运行:

  • Second after moving everything (except the virtualenv directory) create a new virtualenv, activate it and run :

     pip install -r requirements.txt
    

  • 最后在你的情况下,如果你真的没有生成一个 requirements.txt 文件,并且需要使用旧的 site-packages ,有一个肮脏的解决方法我在 gnu/linux 机器上试过一次,但不知何故可以工作,但我不能 100% 确定它是否能正常工作,所以如果你想试一试.

    Finally in your case if you really didn't generated a requirements.txt file, and need to use the old site-packages , there is a dirty workaround which i tried once on a gnu/linux machine and somehow worked but am not 100% sure if it will work properly so if you want give it a try.

    • site-packages 复制到 your-old-virtualenv/lib/python{version}/ 中的某个地方,例如桌面
    • 删除旧的virtualenv,并创建一个新的virtualenv
    • new-virtualenv/lib/python{version}new virtualenv 中的 site-packages 替换为 old 站点包
    • 删除新复制的site-packages
    • 中的__pycache__文件夹
    • 激活新的 virtualenv 并测试是否一切正常.
    • copy the site-packages in your-old-virtualenv/lib/python{version}/ somewhere in your new computer , Desktop for example
    • Delete the old virtualenv, and create a new virtualenv
    • Replace the site-packages in the new virtualenv in new-virtualenv/lib/python{version} with the old site-packages
    • Delete __pycache__ folder in the newly copied site-packages
    • Activate the new virtualenv and test if everything is working .

    注意您应该使用相同的python版本 2 或 3 ,不要期望依赖于 python2 的 virtualenv 与 python3 一起正常运行

    Note that you should use the same python version either 2 or 3 , don't expect a virtualenv that depends on python2 to run properly with python3