activating virtualenv and running python script in bash file

Posted January 25, 2017 171.9k views
PythonUbuntu 16.04

I would like to know how to activate a python virtual env and running a python script inside a bash file.

When I go to my environment directory and do “source name_Env/bin/activate” (without quotes ofcourse) it activates like normal and I can run without getting configparser errors.
But with doing that in bash it seems like it doesnt know the path to the activate file / the activate file

The file:

#! /bin/bash
source name_Env/bin/activate
# virtualenv is now active.

When i try to run it with either “source bashScript.bash” or “bash bashScript.bash” I get the errors:
source: No such file or directoryctivate
bash: No such file or directory line 2: name_Env/bin/activate
and the python configparser error.

The weird thing is that when i type the same thing manually everything works fine but in the bash file not. Is there something wrong in the bash file has it something to do with something else?

(the reason I am using bash file is because I think you cant open a virtualenv in a cronjob but you can link to a file that opens one and runs script)

The directory

        /random directories

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer


Generally, when sourcing a file, you want to use either ./ or the full path, so what I’d recommend is using:

#!/usr/bin/env bash

source ./name_Env/bin/activate


#!/usr/bin/env bash

source /root/environments/name_Env/bin/activate

Though you should also be able to use double-quotes around the source file as well.

#!/usr/bin/env bash

source "./name_Env/bin/activate"


#!/usr/bin/env bash

source "/root/environments/name_Env/bin/activate"

You could even set the file to a variable:

#!/usr/bin/env bash

readonly sourceFile="./name_Env/bin/activate"

source ${sourceFile}


#!/usr/bin/env bash

readonly sourceFile="/root/environments/name_Env/bin/activate"

source ${sourceFile}
  • I tried to use that but still did not completely work. but nevermind I forgot I could just use python3 to run it without environment. this project is the only python one on my droplet so it doesn’t really matter if its not in an virtualenv

    so i just removed the bash script and changed the crontab to

    0,30 * * * * cd /root/environments && /usr/bin/python3 > /tmp/tw$