How to activate Virtualenv when a Python script starts?

31,440

You can just start the example.py with the full path to example-env/bin/python2.

Alternatively change the shebang line of the example.py to use that executable, make that file executable (chmod +x example.py) and leave out python and use the full path to example.py to start it:

#!/full/path/to/example-env/bin/python2
Share:
31,440

Related videos on Youtube

mahieddine
Author by

mahieddine

Updated on September 18, 2022

Comments

  • mahieddine
    mahieddine almost 2 years

    I want to schedule a python script to run using cron on certain dates, the problem is that in order for example.py to work, example-env has to be activated, is there a way to make example.py activate its own virtualenv whenever cron execute it?

    if not, then do I have to create a bash script bash.sh that contains

    #!/usr/bin/env bash
    workon example-env
    python2 example.py
    

    and then schedule that to be executed by cron on certain dates? Or do I have to do something else?

    Both ways are fine with me, I just want to know the correct way to do it. Perhaps I prefer the bash script method, since I have many Python files to run, so if I put them all inside a bash script and schedule that, it seems easier for me, but again I don't know the correct way to do it, therefore I'm asking for advice.

    • Admin
      Admin about 9 years
      It there a “Correct” way? Maybe there is another way.
    • Admin
      Admin about 9 years
      @richard i'll be happy to know about it. I just formulated my question that way coz it never occurred to me that there might be a better way but I love learning