Development Tip

Python 스크립트로 virtualenv 활성화

yourdevel 2020. 10. 14. 21:19
반응형

Python 스크립트로 virtualenv 활성화


Python 스크립트에서 virtualenv 인스턴스를 활성화하고 싶습니다.

나는 그것이 매우 쉽다는 것을 알고 있지만 내가 본 모든 예제는 env 내에서 명령을 실행 한 다음 하위 프로세스를 닫는 데 사용합니다.

bin / activate와 동일한 방식으로 virtualenv를 활성화하고 쉘로 돌아가고 싶습니다.

이 같은:

$me: my-script.py -d env-name
$(env-name)me:

이것이 가능한가?

관련된:

virtualenv›스크립트에서 환경 호출


virtualenv에서 Python 하위 프로세스를 실행하려면 virtualenv의 / bin / 디렉토리에있는 Python 인터프리터를 사용하여 스크립트를 실행하면됩니다.

# path to a python interpreter that runs any python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"

# path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"

subprocess.Popen([python_bin, script_file])

그러나 하위 프로세스 대신 현재 파이썬 인터프리터에서 virtualenv를 활성화하려면 다음 activate_this.py스크립트를 사용할 수 있습니다 .

# doing execfile() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

execfile(activate_this_file, dict(__file__=activate_this_file))

그렇습니다. 문제는 간단하지 않지만 해결책은 있습니다.

먼저 "source"명령을 래핑하는 셸 스크립트를 만들어야했습니다. "." 대신 bash 스크립트의 소스보다 사용하는 것이 더 낫다는 것을 읽었 기 때문입니다.

#!/bin/bash
. /path/to/env/bin/activate

그런 다음 내 파이썬 스크립트에서 간단히 다음과 같이 할 수 있습니다.

import os
os.system('/bin/bash --rcfile /path/to/myscript.sh')

전체 트릭은 --rcfile 인수 내에 있습니다.

파이썬 인터프리터가 종료되면 활성화 된 환경의 현재 셸을 그대로 둡니다.

승리!


virtualenv의 인터프리터에서 스크립트를 실행하는 가장 간단한 솔루션은 스크립트 시작 부분에서 기본 shebang 줄을 virtualenv의 인터프리터 경로로 바꾸는 것입니다.

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

스크립트를 실행 가능하게 만듭니다.

chmod u+x script.py

스크립트를 실행하십시오.

./script.py

짜잔!


공식 Virtualenv 문서 에 따라 다른 Python 환경을 실행하려면 명령 줄에서 실행 가능한 Python 바이너리의 전체 경로를 지정할 수 있습니다 (이전에 virtualenv를 활성화 할 필요 없음).

/path/to/virtualenv/bin/python

virtualenv를 사용하여 명령 줄에서 스크립트를 호출하려는 경우에도 동일하게 적용되며 이전에 활성화 할 필요가 없습니다.

me$ /path/to/virtualenv/bin/python myscript.py

Windows 환경에서도 동일합니다 (명령 줄이든 스크립트이든) :

> \path\to\env\Scripts\python.exe myscript.py

나를 위해 작동하는 간단한 솔루션입니다. 기본적으로 쓸모없는 단계를 수행하는 bash 스크립트가 필요한 이유를 모르겠습니다 (내가 틀렸습니까?)

import os
os.system('/bin/bash  --rcfile flask/bin/activate')

기본적으로 필요한 작업을 수행합니다.

[hellsing@silence Foundation]$ python2.7 pythonvenv.py 
(flask)[hellsing@silence Foundation]$ 

그런 다음 venv를 비활성화하는 대신 Ctrl + D를 누르거나 종료하십시오.
그게 가능한 해결책입니까, 아니면 당신이 원했던 것이 아닌가요?


Child process env is lost on the moment it ceases to exist and moving the environment content from there to parent is somewhat tricky.

What you probably need to do is a spawn a shell script (you can generate one dynamically to /tmp) which will output virtualenv environment variables to a file, which you then read in the parent Python process and put to os.environ.

Or you simply parse activate script in using for line in open("bin/activate") and manually extract stuff and put to os.environ. Tricky, but not impossible.


Top answer only works for python2.x

For Python 3.x use this.

activate_this_file = "/path/to/virtualenv/bin/activate_this.py"

exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))

reference: What is an alternative to execfile in Python 3?


You should create all your virtualenv in one folder, such as virt.

Assuming your virtualenv folder name is virt, if not change it

cd mkdir custom

copy below lines ...

#!/usr/bin/env bash ENV_PATH="$HOME/virt/$1/bin/activate" bash --rcfile $ENV_PATH -i

create a shell script file and paste above lines . . .

touch custom/vhelper nano custom/vhelper

grant executable permission to your file

sudo chmod +x custom/vhelper

now export that custom folder path so that you can find it on command-line by clicking tab...

export PATH=$PATH:"$HOME/custom"

Now you can use it from anywhere by just typing below command ...

vhelper YOUR_VIRTUAL_ENV_FOLDER_NAME

suppose it is abc then ...

vhelper abc

참고URL : https://stackoverflow.com/questions/6943208/activate-a-virtualenv-with-a-python-script

반응형