6

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.

1
  • What does "I haven't been able to do so" mean? Commented Jul 8, 2019 at 13:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.