简体   繁体   English

适用于 Window 和 Linux 的 Python 虚拟环境 Shebang

[英]Python Virtual Environment Shebang for Window and Linux

I have a python file that I'd like to execute using the virtual environment (venv) in the same directory as the file.我有一个 python 文件,我想使用该文件所在目录中的虚拟环境 (venv) 执行该文件。 I'd like it to use this venv regardless of whether the user has activated it or not to avoid accidentally running it without the proper environment.无论用户是否激活它,我都希望它使用这个 venv,以避免在没有适当环境的情况下意外运行它。 I'd like this to work on both Linux and Windows (via Git Bash).我希望它适用于 Linux 和 Windows(通过 Git Bash)。

The issue is that venv puts python under the "bin" directory on Linux but under "Scripts" on Windows and I can't seem to find a way to change this behavior when creating it.问题是 venv 将 python 放在 Linux 上的“bin”目录下,但在 Windows 上的“Scripts”下,我在创建它时似乎找不到改变这种行为的方法。 I tried creating it with Git Bash in hopes that it would "trick" python into using a bin directory instead of Scripts, but that didn't work.我尝试使用 Git Bash 创建它,希望它能“欺骗”python 使用 bin 目录而不是 Scripts,但这不起作用。

The following shebang works well on Linux:以下shebang在Linux上运行良好:

#!.venv3/bin/python

And this one works well on Windows:这个在 Windows 上运行良好:

#!.venv3/Scripts/python

But what will work on both?但是什么对两者都有效? I know that one option would be to create a shell script that activates the environment based on the detected os (using $OSTYPE), but I'd like to avoid this if possible as it isn't otherwise necessary.我知道一种选择是创建一个基于检测到的操作系统(使用 $OSTYPE)激活环境的 shell 脚本,但我想尽可能避免这种情况,因为它不是必需的。

You could use the Windows version of the shebang:您可以使用 shebang 的 Windows 版本:

#!.venv3/Scripts/python

and then create a symbolic link on the Linux side:然后在Linux端创建一个符号链接:

.venv3/Scripts -> .venv3/bin

I just tried this with one of my virtual envs.我刚刚用我的一个虚拟环境尝试了这个。 It worked fine for me.它对我来说很好。 I didn't test the Windows case, but of course, that has to work as we're using the correct shebang for Windows to begin with.我没有测试 Windows 案例,但当然,这必须工作,因为我们开始使用正确的 Windows 系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM