Cross-platform way to specify Python interpreter when running with execv - python

I am currently running a Python scripts both on Linux and Windows 7. The file is executed in an execv style with which I mean that the interpreter is defined in the beginning of the file in a command.
In Windows system, the interpreter specification is:
#!C:\Python26\python.exe
However in Linux this needs to be
#!/usr/bin/python
I would like to run this script in both systems without having to change this line again and again.
I have tried out the following:
#!C:\Python26\python.exe
#!/usr/bin/python
as well as:
#!C:\Python26\python.exe;/usr/bin/python
So: is there any way I could specify multiple interpreters?

Depending on what you're trying to do, this might be a bit heavy-weight, but 0install can run your program will the appropriate Python interpreter for your platform. In your program's XML description, do something like this (e.g. if you want Python >= 2.6, < 3):
<command name="run" path="myprog.py">
<runner interface="http://repo.roscidus.com/python/python">
<version not-before="2.6" before="3"/>
</runner>
</command>
See: http://www.0install.net/local-feeds.html
This will also make 0install download a suitable version of Python if the user doesn't have it already.
Note that you may want to do this even if you're only targetting Linux, because with Python 3 there is no single #! line that works on all platforms (some platforms, e.g. Arch, require "python2" not "python", while others, e.g. Debian, don't provide "python2", only "python").

#!/usr/bin/env python
That will call the env program to search your PATH for a Python executable.
If you need to ensure a specific version of Python you can do e.g.:
#!/usr/bin/env python3.11

Is there any way I could specify multiple interpreters ?
You don't need to. On Windows (at least as long as you don't have CygWin or similar installed), the Shebang line is treated as a normal Python comment; that means, it is ignored. Windows knows that it should run .py and .pyw files with the Python interpreter, because it is told that upon installation of Python.

Related

“./file.py” VS “python file.py”

What is the difference between the ./file.py & the python file.py commands?
What I See
I usually see people using ./file.py when they are using a terminal-text editor like vim or nano or emacs OR when they are using linux based operating systems like Ubuntu or Arch Linux.
And I usually see python file.py from the ones who are using some other operating system. I’m probably not correct. But if it is so, what is the difference between the both?
Thank You!
on linux-based operating systems, when you execute a text file, if it starts with #!/bin/python (shebang syntax), it will actually do /bin/python filename, so it is faster to do this than having to type python all the time, it is easier to make it an executable file, but there are no major differences
In Linux and Unix operating systems, you can execute an executable (./file.py) without explicitly specifying it as a python file, while you can as well execute same file.py as python file.py in both Windows and non-Windows Operating system.
For this python file to be executed without explicitly prefixing python to it, it must surely meet these two requirements:
Must contain a shebang line:
A sha-bang/shebang line is a line of code which consists of characters that tells the loader to use the specified interpreter, just as stated in the docs
If the first line of a script file starts with #!, it is known as a
“shebang” line. Linux and other Unix like operating systems have
native support for such lines and they are commonly used on such
systems to indicate how a script should be executed. This launcher
allows the same facilities to be used with Python scripts on Windows
and the examples above demonstrate their use.
To allow shebang lines in Python scripts to be portable between Unix
and Windows, this launcher supports a number of ‘virtual’ commands to
specify which interpreter to use. The supported virtual commands are:
/usr/bin/env python
/usr/bin/python
/usr/local/bin/python
python
Must be an executable file
In Linux and Unix OS, files are treated separately depending on their permissions and mode, you must make file.py an executable before calling it without explictly prefixing python/python3, to make file.py executable, you need to change the mode to an executable by running chmod +x file.py from the file directory in Linux terminal.

Other than swapping order of paths to python folders in system variable 'PATH' - what are the ways to swap python versions?

I can change the order to python2,3 folders in the system PATH variable. But what are other ways to do this?
There should be more elegant way to change versions of python i want to run.
e.g. in console:
python file.py #will run python2
and after i change python command to use python3, it should be the same:
python file.py #will use python3
I suppose you are trying to run your script with the correct interpreter depending on which python version was used. On Unix/Linux this is done with a so called “shebang” which is written in the very first line of the file. E.g.:
#!/usr/bin/env python3.6
If your installation of Python3 is newer than Python 3.3 you can use the python launcher for windows, which should be able to launch the correct version of Python depending on the shebang, even on window.
Also see here for more informations on shebangs.
If your concern is what Python version is executed when calling python in a console, then an alias or a stub script are the two ways to go.
This post will explain you how you can do this on Windows.
The alias way, just like it would be on a Unix system, is to create an alias, either temporary to the session or permanent, so that python now means C:\Python27\python, or whatever version you want.
The script approach consists in putting a script named python in a directory referred to in your PATH, and have that script run the right version of Python.
I highly doubt that this will affect all the batch scripts that call python, but it will definitely fire the right Python when you'll type python in a console.
Now, if you're concerned about what version a script is executed with, you can specify an explicit version with a shebang line, or manually select it by right-clicking the .py file and clicking open with.

How do i know if a script is to be run with Python 2 or Python 3 [duplicate]

How do I, in the main.py module (presumably), tell Python which interpreter to use? What I mean is: if I want a particular script to use version 3 of Python to interpret the entire program, how do I do that?
Bonus: How would this affect a virtualenv? Am I right in thinking that if I create a virtualenv for my program and then tell it to use a different version of Python, then I may encounter some conflicts?
You can add a shebang line the to the top of the script:
#!/usr/bin/env python2.7
But that will only work when executing as ./my_program.py.
If you execute as python my_program.py, then the whatever Python version that which python returns will be used.
In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.
Perhaps not exactly what you asked, but I find this to be useful to put at the start of my programs:
import sys
if sys.version_info[0] < 3:
raise Exception("Python 3 or a more recent version is required.")
I would use the shebang #!/usr/bin/python (first line of code) with the serial number of Python at the end
Then run the Python file as a script, e.g., ./main.py from the command line, rather than python main.py.
It is the same when you want to run Python from a Linux command line.
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you would need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run:
C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
You can't do this within the Python program, because the shell decides which version to use if you a shebang line.
If you aren't using a shell with a shebang line and just type python myprogram.py it uses the default version unless you decide specifically which Python version when you type pythonXXX myprogram.py which version to use.
Once your Python program is running you have already decided which Python executable to use to get the program running.
virtualenv is for segregating python versions and environments, it specifically exists to eliminate conflicts.
For those using pyenv to control their virtual environments, I have found this to work in a script:
#!/home/<user>/.pyenv/versions/<virt_name>/bin/python
DO_STUFF
I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths.
So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).
While working with different versions of Python on Windows,
I am using this method to switch between versions.
I think it is better than messing with shebangs and virtualenvs
install python versions you desire
go to Environment Variables > PATH
(I assume that paths of python versions are already added to Env.Vars.>PATH)
suppress the paths of all python versions you dont want to use
(don't delete the paths, just add a suffix like "_sup")
call python from terminal
(so Windows will skip the wrong paths you changed,
and will find the python.exe at the path you did not suppressed,
and will use this version after on)
switch between versions by playing with suffixes

Attempting to make python file executable on mac. Bad interpreter, permission denied [duplicate]

Should I put the shebang in my Python scripts? In what form?
#!/usr/bin/env python
or
#!/usr/local/bin/python
Are these equally portable? Which form is used most?
Note: the tornado project uses the shebang. On the other hand the Django project doesn't.
The shebang line in any script determines the script's ability to be executed like a standalone executable without typing python beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use is important.
Correct usage for (defaults to version 3.latest) Python 3 scripts is:
#!/usr/bin/env python3
Correct usage for (defaults to version 2.latest) Python 2 scripts is:
#!/usr/bin/env python2
The following should not be used (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):
#!/usr/bin/env python
The reason for these recommendations, given in PEP 394, is that python can refer either to python2 or python3 on different systems.
Also, do not use:
#!/usr/local/bin/python
"python may be installed at /usr/bin/python or /bin/python in those
cases, the above #! will fail."
―"#!/usr/bin/env python" vs "#!/usr/local/bin/python"
It's really just a matter of taste. Adding the shebang means people can invoke the script directly if they want (assuming it's marked as executable); omitting it just means python has to be invoked manually.
The end result of running the program isn't affected either way; it's just options of the means.
Should I put the shebang in my Python scripts?
Put a shebang into a Python script to indicate:
this module can be run as a script
whether it can be run only on python2, python3 or is it Python 2/3 compatible
on POSIX, it is necessary if you want to run the script directly without invoking python executable explicitly
Are these equally portable? Which form is used most?
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. It is bad if some tool breaks if you activate a virtualenv in your shell. Luckily, the correct shebang is created automatically in most cases by setuptools or your distribution package tools (on Windows, setuptools can generate wrapper .exe scripts automatically).
In other words, if the script is in a source checkout then you will probably see #!/usr/bin/env python. If it is installed then the shebang is a path to a specific python executable such as #!/usr/local/bin/python (NOTE: you should not write the paths from the latter category manually).
To choose whether you should use python, python2, or python3 in the shebang, see PEP 394 - The "python" Command on Unix-Like Systems:
... python should be used in the shebang line only for scripts that are
source compatible with both Python 2 and 3.
in preparation for an eventual change in the default version of
Python, Python 2 only scripts should either be updated to be source
compatible with Python 3 or else to use python2 in the shebang line.
If you have more than one version of Python and the script needs to run under a specific version, the she-bang can ensure the right one is used when the script is executed directly, for example:
#!/usr/bin/python2.7
Note the script could still be run via a complete Python command line, or via import, in which case the she-bang is ignored. But for scripts run directly, this is a decent reason to use the she-bang.
#!/usr/bin/env python is generally the better approach, but this helps with special cases.
Usually it would be better to establish a Python virtual environment, in which case the generic #!/usr/bin/env python would identify the correct instance of Python for the virtualenv.
The purpose of shebang is for the script to recognize the interpreter type when you want to execute the script from the shell.
Mostly, and not always, you execute scripts by supplying the interpreter externally.
Example usage: python-x.x script.py
This will work even if you don't have a shebang declarator.
Why first one is more "portable" is because, /usr/bin/env contains your PATH declaration which accounts for all the destinations where your system executables reside.
NOTE: Tornado doesn't strictly use shebangs, and Django strictly doesn't. It varies with how you are executing your application's main function.
ALSO: It doesn't vary with Python.
You should add a shebang if the script is intended to be executable. You should also install the script with an installing software that modifies the shebang to something correct so it will work on the target platform. Examples of this is distutils and Distribute.
Sometimes, if the answer is not very clear (I mean you cannot decide if yes or no), then it does not matter too much, and you can ignore the problem until the answer is clear.
The #! only purpose is for launching the script. Django loads the sources on its own and uses them. It never needs to decide what interpreter should be used. This way, the #! actually makes no sense here.
Generally, if it is a module and cannot be used as a script, there is no need for using the #!. On the other hand, a module source often contains if __name__ == '__main__': ... with at least some trivial testing of the functionality. Then the #! makes sense again.
One good reason for using #! is when you use both Python 2 and Python 3 scripts -- they must be interpreted by different versions of Python. This way, you have to remember what python must be used when launching the script manually (without the #! inside). If you have a mixture of such scripts, it is a good idea to use the #! inside, make them executable, and launch them as executables (chmod ...).
When using MS-Windows, the #! had no sense -- until recently. Python 3.3 introduces a Windows Python Launcher (py.exe and pyw.exe) that reads the #! line, detects the installed versions of Python, and uses the correct or explicitly wanted version of Python. As the extension can be associated with a program, you can get similar behaviour in Windows as with execute flag in Unix-based systems.
When I installed Python 3.6.1 on Windows 7 recently, it also installed the Python Launcher for Windows, which is supposed to handle the shebang line. However, I found that the Python Launcher did not do this: the shebang line was ignored and Python 2.7.13 was always used (unless I executed the script using py -3).
To fix this, I had to edit the Windows registry key HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Python.File\shell\open\command. This still had the value
"C:\Python27\python.exe" "%1" %*
from my earlier Python 2.7 installation. I modified this registry key value to
"C:\Windows\py.exe" "%1" %*
and the Python Launcher shebang line processing worked as described above.
Answer: Only if you plan to make it a command-line executable script.
Here is the procedure:
Start off by verifying the proper shebang string to use:
which python
Take the output from that and add it (with the shebang #!) in the first line.
On my system it responds like so:
$which python
/usr/bin/python
So your shebang will look like:
#!/usr/bin/python
After saving, it will still run as before since python will see that first line as a comment.
python filename.py
To make it a command, copy it to drop the .py extension.
cp filename.py filename
Tell the file system that this will be executable:
chmod +x filename
To test it, use:
./filename
Best practice is to move it somewhere in your $PATH so all you need to type is the filename itself.
sudo cp filename /usr/sbin
That way it will work everywhere (without the ./ before the filename)
If you have different modules installed and need to use a specific
python install, then shebang appears to be limited at first. However,
you can do tricks like the below to allow the shebang to be invoked
first as a shell script and then choose python. This is very flexible
imo:
#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
echo Using preferred python $PREFERRED_PYTHON
exec $PREFERRED_PYTHON "$0" "$#"
elif [ -x $ALTERNATIVE_PYTHON ]; then
echo Using alternative python $ALTERNATIVE_PYTHON
exec $ALTERNATIVE_PYTHON "$0" "$#"
else
echo Using fallback python $FALLBACK_PYTHON
exec python3 "$0" "$#"
fi
exit 127
'''
__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())
Or better yet, perhaps, to facilitate code reuse across multiple python scripts:
#!/bin/bash
"true" '''\'; source $(cd $(dirname ${BASH_SOURCE[#]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$#"; exit 127; '''
and then select.sh has:
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3
if [ -x $PREFERRED_PYTHON ]; then
CHOSEN_PYTHON=$PREFERRED_PYTHON
elif [ -x $ALTERNATIVE_PYTHON ]; then
CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
else
CHOSEN_PYTHON=$FALLBACK_PYTHON
fi
This is really a question about whether the path to the Python interpreter should be absolute or logical (/usr/bin/env) with respect to portability.
My view after thoroughly testing the behavior is that the logical path in the she-bang is the better of the two options.
Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments is something I really need a solid answer to. Encountering other answers on this and other Stack Overflow sites which talked about the issue in a general way without supporting proofs, I've performed some really granular testing & analysis on this very question on Unix.SE.
For files that are intended to be executable from the command-line, I would recommend
#! /usr/bin/env python3
Otherwise you don't need the shebang (though of course it doesn't harm).
If you use virtual environments like with pyenv it is better to write #!/usr/bin/env python
The pyenv setting will control which version of python and from which file location is started to run your script.
If your code is known to be version specific, it will help others to find why your script does not behave in their environment if you specify the expected version in the shebang.
If you want to make your file executable you must add shebang line to your scripts.
#!/usr/bin/env python3
is better option in the sense that this will not be dependent on specific distro of linux but could be used on almost all linux distro since it hunts for the python3 path from environment variables, which is different for different distros of linux.
whereas
#!/usr/local/bin/python3
would be a distro specific path for python3 and would not work if python3 is not found on this path, and could result in confusion and ambiguity for developer when migrating from one distro to another of linux.
Use first
which python
This will give the output as the location where my python interpreter (binary) is present.
This output could be any such as
/usr/bin/python
or
/bin/python
Now appropriately select the shebang line and use it.
To generalize we can use:
#!/usr/bin/env
or
#!/bin/env

Running a python program after setting the execute bit in Python 3

I was going through Google's Python instructions and it quotes:
The commands above are the simplest way to run python programs. If the
"execute bit" is set on a .py file, it can be run by name without
having to type "python" first. Set the execute bit with the "chmod"
command like this:
Where it proceeds to give me this code to run on my terminal:
~/google-python-exercises$ chmod +x hello.py
~/google-python-exercises$ ./hello.py ## now can run it as ./hello.py
Hello World
However when I type in ./hello.py, I get:
So is this something to do with me using Python 3 when this could be a command for Python 2?
EDIT
I just realised that this can only be run on a Linux/Mac. How does one go about doing this on a Windows?
You need to associate the file extension with Python properly. This should happen by default if you install system wide (which requires administrator privileges), but if you're using a third party distribution, it's not guaranteed, and it may require a reboot even so.
For more details running Python on Windows, see the Python on Windows docs. It looks like if you omitted the launcher from your Python install, it won't have registered the file extensions; it may be worth reinstalling properly to fix that.
Otherwise, if you can't get file extension associations working, just run:
python hello.py
or starting with 3.3 and later, you can use:
py hello.py
which lets you provide an argument to py.exe to change which installed version of Python to use (if desired).
You wouldn't use ./hello.py on Windows at all, because that's the wrong directory separator (Windows sometimes allows forward slashes, but in DOS prompts, that looks like trying to launch a program named . with the switch /hello.py). You'd use plain hello.py (Windows always searches the current working directory) or .\hello.py if you want to be explicit.
Do you have a shebang as the first line in hello.py?
something like:
#!/usr/bin/env python3

Categories