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

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

Related

Opening Python script mode on a MacBook

I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.
There is no 'script mode'. You can create a Python script using TextEdit or another editor, save it as myfile.py, and then run it with python myfile.py.
for running what you are calling 'script version' of python you should choose a python file to run and make sure is written in the same or in a compatible version to the python you are running it with (python2, python3)
For running an example script:
python main.py
You need to be in the directory containing the file so make sure you are there before running the command. Using python runs the first version of python you installed, so if you want to use an other you should use:
python2 main.py
python3 main.py
etc
Assuming you've stored your script in a file named itworks.py, the simplest thing is to type the command python3 itworks.py in a terminal window after you've moved to the directory containing the script. Alternatively, you can type python3 followed by a space, then locate your python script in the Finder and drag and drop it into the terminal. This will expand to the full path to the file, allowing you to run a script located elsewhere than your current directory. Don't forget to press return...
In older versions of MacOS you could say python, but that uses python 2 which is no longer supported so you should go with python3 for any new development. (With MacOS Ventura, python 2 seems to have been removed.)
If you have multiple versions of python, you can use the command which -a python3 (or python) to see all versions on your PATH, and the order in which they will be found. PATH works on a first-come-first-served basis, but you can override by using the fully qualified path name to an alternative python.
Yet another solution, for when you want a more permanent script you will use many times in the future, is to use a "shebang" line as the first line of your script. For example, I wrote the following tiny demo:
#!/usr/bin/env python3
print('It works!')
The first line says to parse this script with the first python3 interpreter found in your current environment's PATH. You could replace that with an explicit path such as #!/opt/homebrew/bin/python3. Now make the script executable: chmod a+x itworks.py. You can now run the script from the current directory by typing ./itworks.py. (The leading ./ tells your shell you know it's in the current directory, and is intended as protection against trojan horse scripts.) If you want to be able to use the now-executable script from anywhere, add it to a directory on your path such as /usr/local/bin, and you'll be able to run it by just typing itworks.py.

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 would I allow others to use my script from anywhere in the shell without having to type out the file extension?

Excuse the awkward question wording.
I've made a script. I would like for others to download it from github, and run it by typing programName argument1 argument2, similar to any other popular app used through the terminal such as Jupyter or even opening Atom/Sublime/etc. (ex:jupyter notebook, atom .). However, unlike Jupyter or sublime, my script isn't launching another app, it's a small app meant to be used in the shell.
Currently, to use my script, one must type into the command line python programName.py arg1 etc from within the file's directory.
How do I allow others to dl it and use it from anywhere (not having to be within the directory), without having to type out the whole python programName.py part, and only having to type programName arg1?
This blog post explains step by step how to create a distribution that you can install and it would turn into an executable.
You can refer to this github repo for a sample application.
The full documentation of setuptools is available here.
In general, you should configure your setup.py in order to use the command in the entry-point option:
setup(
name = "your_app_name",
packages = ["package_name"],
entry_points = {
"console_scripts": ['cmd_name = package_name.package_name:main']
},
....
)
This solution would work on every OS where you have installed python.
Your script may need to have an interpreter, "shebang", besides being "reachable" by the $PATH
#!interpreter [optional-arg]
For example, you could have something like
#!/usr/bin/env python
or to force a specific version
#!/usr/local/bin/python2.7
Next, your script needs to be available within the $PATH, check this answer that covers that part: https://unix.stackexchange.com/q/29608/53084
You can simply add your script to PATH variable in order to launch it from anywhere.
In Linux distros, you can simply do it by using a bash command PATH=$PATH:/path/to/your/script.
Make sure you don't have the space around the "=" operator.
Now, the second thing is you don't want your script to be named as pythonProgram.py.You can simply remove the extension .py from PythonProgram.py by adding a single line to the starting of your script.
Open up your script and at the very begining type #!/usr/bin/python.This should be the first line of your code.This line is called shebang and is used to tell the bash which interpreter to be used for compiling the script.
If everything went right, you will be able to run your script as pythonProgram arg1.
In addition to mabe02: Python is a scripting language and usually not compiled, which means you will need an interpreter to run your program.
Programms made in C f.e. can be run on its own because they were compiled into machine code by a compiler.
An interpreter is similar to a compiler as it reads your script and interprets it at runntime. That is why you need to write python before your programm, to tell your computer to interpret your script on runntime, using python. This doesn't mean that there are no possibilities to compile python as can be seen in the other answer and in this link Can a python program be run on a computer without Python? What about C/C++? (py2exe and py2app).

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

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

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.

Categories