简体   繁体   中英

Automatically open a virtual environment when calling a python script in Windows

This question has been asked before, but the answers are all several years old and I could not get any to work for me, so I would appreciate some help.

The question is simple, really: I have a python script, and a virtual environment I want it to run in when I double-click it, or call it from another program. How can I achieve this?

Some ideas

Shebang

Place a shebang pointing to the Python interpreter inside the virtual environement with the full path at the top of the script.

#!/path/to/my/venv/bin/python

import sys

print(sys.executable)

Shell/batch script

Write a shell script wrapping the call to the actual Python script:

#!/usr/bin/env sh

/path/to/my/venv/bin/python /path/to/my/script.py

Python wrapper

#!/usr/bin/env python3

import subprocess

command = [
    '/path/to/my/venv/bin/python',
    '/path/to/my/script.py',
]
subprocesss.check_call(command)

you must add packages directory address to your sys.path

sys.path a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module.

add line below to top of your script, now you can double click on script file and every thing must work fine

import sys; sys.path.append("./<environment path>/Lib/site-packages")

this is simple solution however, as sinoroc said it's not good solution because in this situation you are using system interpreter not virtual environment interpreter so i wouldn't be surprised if things don't work as expected.


also you can download all packages that you need and extract them into single folder and add that folder to sys.path

first download packages you need with command below

pip download <package names> --dest <directory name>

for example:

pip download requests --dest packages

at the end add folder contain you packages to your path

import sys; sys.path.append("./<packages directory>")

Recommended Solution

the best solution is that write little batch script for windows or shell script for linux that automatically active virtual environment and then run your script

first create file with .bat extention for windows or .sh extension for linux and then add line below to it

for .bat file

<environment path>\Scripts\activate && python <script name>.py

for .sh file

source <environment path>/bin/activate && python <script name>.py

now you can click on this batch script * .bat file or shell script * .sh file and everything work's fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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