Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python script without activating virtual environment

I want to run a python script from the command line but I'd like to eliminate the need to activate the virtual environment first. If possible, I'd also like to eliminate the need to call python before the script. I saw somewhere that adding #!/usr/bin/env python to the start of the script will work but I haven't been able to do so.

like image 883
C.Acarbay Avatar asked Jul 08 '19 13:07

C.Acarbay


2 Answers

Use chmod +x script.py to make your script executable. The #!shebang selects an interpreter.

You can call an executable from the shell like so:

/path/to/script.py

Or:

cd /path/to; ./script.py

Alternatively, you can put your script in one of the directories defined by $PATH, which will let you call it just like any other utility.

like image 181
vintnes Avatar answered Oct 22 '22 04:10

vintnes


Supposing a structure like this in your home folder

home
- <user_name>
-- project_name
--- env
--- main.py

Where env is your virtual environment, you can use a shebang like this:

#!env/bin/python

at the very beginning of your main.py file. Then you should make your file executable with:

chmod +x main.py

Now if you run your code (from project_name folder) with:

./main.py

The code contained in main.py will be executed.

If you want to be able to run main.py from a different location, you should use an absolute path in the shebang, like:

#!/absolute/path/to/bin/python

So it will be something like:

#!/home/<user_name>/project_name/env/bin/python
like image 36
Manuel Fedele Avatar answered Oct 22 '22 05:10

Manuel Fedele