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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With