System:
- Operating System: CentOS Linux 7 (Core) / CentOS Linux release 7.7.1908 (Core)
- Kernel: Linux 3.10.0-1062.4.1.el7.x86_64
- Server from Provider – i am just a user
Hello this is my Path to my virtual env activate, which is currently running a django app.
/home/username/.local/env_myapp/bin/activate
if run the command
$ source /home/username/.local/env_myapp/bin/activate
The env$ (my_env)
starts in the terminal.
I wanted to write a little script to automate the env starting without putting the whole path every time in the console.
so i looked into the activate
file…
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
alright so u wrote this few lines in my script.
my_env
#!/usr/bin/bash
source /home/username/.local/env_myapp/bin/activate
echo "check - activate env"
exit
- if i run
$ my_env
it only echos "check – activate" - if i run
$ source my_env
it runs to echo "check – activate" and then my terminal in VScode vanishes.
Question
So how to activate python env via linux script correctly?
Dear Stackoverflow, this Question was about how to start the env via script and not about exit
– as you flag this as a duplicate. Furthermore ny question is solved with the comments under my question, but i can not "solve" it. So wrote an answer down below – see "update" and credits to answers.
3
Answers
Update
thanks to @Charles Duffy @alaniwi
now the Script starts my env in the terminal.
(did know how to close the Question, via Question comments. so i wrote the answers of @Charles Duffy @alaniwi here)
Read Advanced Linux Programming, syscalls(2) and execve(2) (almost every Linux program except
/sbin/init
is started withexecve
).So you might start your python script with a shebang, so
#!/usr/bin/python
(and make it executable with chmod(1)).Be aware of your
$PATH
variable (see environ(7) and exec(3)).Your Unix shell is probably GNU bash (see also getpwent(3) and passwd(5)), so read its documentation (I personally prefer zsh) or at least bash(1)
You can add a shell function that automatically activates the environment when you
cd
into the directory. (This assumes that your pyenv is in the Python project directory, not e.g., in your$HOME/pyenv
or such.)Either copy the above into your
~/.bashrc
orsource
it from there.