简体   繁体   English

在不激活虚拟环境的情况下运行Python脚本

[英]Run Python script without activating virtual environment

I want to run a python script from the command line but I'd like to eliminate the need to activate the virtual environment first. 我想从命令行运行python脚本,但是我想不需要先激活虚拟环境。 If possible, I'd also like to eliminate the need to call python before the script. 如果可能的话,我也想消除在脚本之前调用python的需要。 I saw somewhere that adding #!/usr/bin/env python to the start of the script will work but I haven't been able to do so. 我在某处看到可以在脚本的开头添加#!/usr/bin/env python可以正常工作,但我一直无法这样做。

Use chmod +x script.py to make your script executable. 使用chmod +x script.py使脚本可执行。 The #!shebang selects an interpreter. #!shebang选择一个口译员。

You can call an executable from the shell like so: 您可以像这样从shell调用可执行文件:

/path/to/script.py

Or: 要么:

cd /path/to; ./script.py

Alternatively, you can put your script in one of the directories defined by $PATH , which will let you call it just like any other utility. 另外,您可以将脚本放入$PATH定义的目录之一,这将使您像调用其他任何实用程序一样调用它。

Supposing a structure like this in your home folder 在您的文件夹中假设这样的结构

home
- <user_name>
-- project_name
--- env
--- main.py

Where env is your virtual environment, you can use a shebang like this: env是您的虚拟环境的地方,可以使用如下所示的shebang

#!env/bin/python

at the very beginning of your main.py file. main.py文件的开头。 Then you should make your file executable with: 然后,您应该使用以下命令使文件可执行:

chmod +x main.py

Now if you run your code (from project_name folder) with: 现在,如果您使用以下命令运行代码(来自project_name文件夹):

./main.py

The code contained in main.py will be executed. main.py中包含的代码将被执行。

If you want to be able to run main.py from a different location, you should use an absolute path in the shebang , like: 如果您希望能够从其他位置运行main.py ,则应在shebang中使用绝对路径,例如:

#!/absolute/path/to/bin/python

So it will be something like: 因此,它将类似于:

#!/home/<user_name>/project_name/env/bin/python

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

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