Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what shebang to use for python scripts run under a pyenv virtualenv

When a python script is supposed to be run from a pyenv virtualenv what is the correct shebang for the file?

As an example test case, the default python on my system (OSX) does not have pandas installed. The pyenv virtualenv venv_name does. I tried getting the path of the python executable from the virtualenv.

$ pyenv activate venv_name (venv_name)$ which python /Users/username/.pyenv/shims/python 


So I made my example script.py:

#!/Users/username/.pyenv/shims/python import pandas as pd print 'success' 


But when I tried running the script, I got an error:

(venv_name) $ ./script.py ./script.py: line 2: import: command not found ./script.py: line 3: print: command not found 


Although running that path on the command line works fine:

(venv_name) $ /Users/username/.pyenv/shims/python script.py success  (venv_name) $ python script.py # also works success 

What is the proper shebang for this? Ideally, I want something generic so that it will point at the python of whatever my current venv is.

like image 492
xgord Avatar asked May 19 '17 18:05

xgord


People also ask

How do I run a Python script in a virtual environment?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .

Where should I put shebang in Python?

If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher). Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/. virtualenvs/project/bin/python .

What is the issue with using the following shebang line #!/ Usr bin env Python?

The contents of the shebang line are therefore automatically ignored by the interpreter. A common use of the env command is to launch interpreters, by making use of the fact that env will search $PATH for the command it is told to launch.

Should I use shebang in Python?

Whether using the shebang for running scripts in Python is necessary or not, greatly depends on your way of executing scripts. The shebang decides if you'll be able to run the script as a standalone executable without typing the python command. So, if you want to invoke the script directly – use the shebang.


1 Answers

I don't really know why calling the interpreter with the full path wouldn't work for you, I use it all the time, but if you want to use the python interpreter that is in your environment you should do:

#!/usr/bin/env python 

That way you search your environment for the python interpreter to use.

like image 116
DSLima90 Avatar answered Oct 01 '22 19:10

DSLima90