Compiling Python - python

How can I compile and run a python file (*.py extension)?

python yourfile.py
You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.
http://www.python.org/download/

Python compiles its files to bytecode before executing them. That means you have to have a Python interpreter installed on the target machine.
If you don't want to install Python on the target machine use py2exe, py2app or something similar.

If you just want to compile sources, without running them, you can do this
compileall.py <directory>
this command will compile python code in that directory recursively
compileall script is usually located in directory like
/usr/local/lib/python2.6
i.e. <prefix>/lib/python2.6 (or similar, depending on prefixes set a python configuration)
As Lulu suggests, you should make sure that resulting .pyc and .pyo files are executable by the users you care about.
compileall can also be used as a module
import compileall
compileall.compile_dir(path)

Python is an interpreted language, so you don't need to compile it; just to run it. As it happens, the standard version of python will compile this to "bytecode", just like Java etc. does, and will save that (in .pyc files) and run it next time around, saving time, if you haven't updated the file since. If you've updated the file, it will be recompiled automatically.
You can also run python with a -O flag, which will generate .pyo files instead of .pyc. I'm not sure it makes much difference. If speed is important, use psyco.
And yes, on Unix (including Linux, BSD, and Mac OS X, or in a unix shell on windows) you can use a shebang line at the top of the file to make the file automatically run using python. On windows, the equivalent is to associate .py files with python.exe, and then make sure your PATHEXT environment variable includes ".PY" extensions.
However, for windows, you more likely want to write a gui program in python (possibly using PyQT4 and ERIC4) which has a .pyw file as its main script, and has .pyw associated with pythonw (which comes with python on windows). This will let you run python scripts on windows just like other GUI programs. For publishing and distribution, you probably want to compile to an executable file using something like py2exe, as others mentioned.

To add to Paul McMillan's answer, if you are on Windows and you have Python installed, then any files ending with the extension ".py" should be associated with the python executable, allowing you to run it like so:
> myfile.py
In *nix, you can begin the file with #!/usr/bin/python and run it like so:
$ ./myfile.py
In *nix systems, if the first two characters of a file are #! then it will execute the file with the specified executable, which I set here to be /usr/bin/python.

If you want to transform a python source file into a double-clickable .exe on windows, you can use py2exe, which can help you build an easy to distribute package.

On most Unix-like systems, you can use the shebang to tell the operating system which interpreter should be called. You simply put
#!/path/to/python
in the first line of your file, where of course you have to replace "/path/to/" with the path you have on your system. In most cases this would be "/usr/bin/python" or "/usr/local/bin/python". On unix systems you could also look for the path with
"#!usr/bin/env python"
or invoke the command
which python
to find the path.
You can then run your program with the command
./yourprogram.py
If it tells you that you do not have permission to do so, you have to use the command
chmod a+x yourprogram.py

Answer for Windows
first you must install python
then set path variable
after that write your python program and save
think there is a python program that name "hello.py"
open cmd.exe
then goto the path that you saved your "hello.py" file,
and then type python hello.py and press enter key.
now the python code is automatically compile and show the result.

Related

When using Python Windows Launcher, is there any way to prevent having to type full path?

In Windows 8, I often use the Python Windows Launcher like
py C:/long/long/long/long/long/path/to/prog.py ...
Is there any way to set some environment setting, such as PATH or PYTHONPATH etc, to prevent having to type the full path to prog.py?
From my basic knowledge/research, PATH only helps with the py part of the command line and PYTHONPATH only helps with imports within prog.py, so how do I deal with the path to prog.py itself??
Notes:
I cannot modify the code, not even the "shebang" line, since it is needed to work on other platforms.
I cannot cd to the directory containing the programs to run them, because the programs will do something based on the directory they're run in (they'll modify the files in the directory they're run in).
I know that if I associate .py extension with the Python Windows Launcher, then I can run prog.py as the first item in the command line, and thus use PATH, but currently my .py extension is associated with my favorite editor and I'd like to keep it that way if possible (so I can double-click any Python file in Windows Explorer and edit it).
However, if someone suggests a solution where I can have a different association for Windows Explorer versus the command line, then that could be a potential solution! (i.e. in Windows Explorer, .py opens with the editor, while on command line, .py runs with Python Windows Launcher)
Add your long path to PYTHONPATH, then invoke your program as such:
python -m prog
Python will search for a module called prog and then run it as the main module.
Answer to my own question: Actually, I'm so silly. I could just set a variable for each program path (there are only a few programs paths), i.e.. prog=C:/long/path/to/prog.py and then do py %prog% .... I guess I figured out an answer to my own question that was acceptable to me.
Update: I just found something even better. I can do
doskey prog=py C:/long/path/to/prog.py $*
and then simply prog ... afterward
Now I just have to do some crazy stuff to get the doskey command into a file that will be run every time I start a console, as described here: https://stackoverflow.com/a/21040825/5182136

Why don't I have to add 'python' before invoking Python script?

I am new to programming, and Python is my first language.
I've added Python to my Path, but when I use the Command Prompt, I don't have to add python before myscript.py as opposed to many tutorials I've seen. Here is an example:
C:\User\MyName>Welcome.py
Welcome to Python
Python is fun
When I enter 'python', there is a subsequent error:
C:\User\MyName>python Welcome.py
python: can't open file 'Welcome.py': [Errno 2] No such file or directory
Do I really need the 'python'?
Thanks in advance!
If you followed the Python on Windows FAQ, it seems that the standard Python installer has already taken the liberty of associating .py files with an open command to ..\..\Python\python.exe "%1" %*.
How do I make Python scripts executable?
On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.
Who'd have thunk! This isn't the way it used to be four years ago when I first installed Python on my Windows machine.
Yes and no.
It really depends on how the script is written.
On most unix systems (Linux, Mac OS), you could include #!/bin/python to the top of (as the first line of) your script and therefore execute it by just calling the filename on the command line. That first line tells the shell that this file contains a python program. The shell then uses the python interpreter to execute the file (translation: it translates your $ Welcome.py to $ /bin/python Welcome.py <- note that python is being called explicitly and that it's the same path as what's on the first line of your file).
Presumably, the Windows OS can also be instructed in the same way, though I have never been able to do it myself, nor have I tried very hard (I moved away from windows about 5 years ago). This is why you'll need to explicitly call python.
Calling python tells the OS: "hey! open that program called python and tell it to run the file Welcome.py". This is exactly what the command /bin/python Welcome.py does on a unix system
When you install python on windows with a regular installer, .py files are associated with the python.exe you installed. When you type Welcome.py, Windows searches the local directory and then all paths in the PATH variable for a program called Welcome.py and runs it via python. Since this worked for you, it means that Welcome.py is somewhere on your path or in your local directory.
You can figure out your file associations with the assoc .py and ftype Python.File commands. The echo %PATH% and echo %PATHEXT% commands are also useful.
When you type python Welcome.py, Windows searches all paths in the PATH variable for a program that starts with 'python' and ends with an extension in PATHEXT. It finds 'python.exe' and runs it. Python in turn looks for a script called Welcome.py in the current directory. Since this didn't work for you, it means that Welcome.py is not in your local directory. It would have worked if you had given the right path to Welcome.py.
You can find out where Welcome.py is with the (not surprisingly) where Welcome.py command.
If you only have a single python installation, there is no need to call python myscript.py ....

Distributing Python scripts without .py extension

if I'm writing a package in Python for distribution and I put some scripts to be regarded as executables in the scripts of setup.py, is there a standard way to make them not have the *.py extension? Is it sufficient to just make files that do not have the .py extension, or is anything extra needed? Will removing the .py from the filename that break any of the functionality associated with Python tools like setup.py/distutils etc? Thanks.
The .py extension is only necessary when you want to import the model AFAICT. Remember that pip, easy_install, and the like are simply executable files with the shebang at the top. The only OS that relies on file extensions for execution purposes is Windows.
If you need Windows compatibility then either don't remove the .py extension or use setuptools' entry_points option that automatically generates appropriate for the system script files e.g., to install pip.main() function as a script, pip specifies in setup.py:
entry_points=dict(console_scripts=['pip=pip:main',
'pip-%s=pip:main' % sys.version[:3]]),
It makes sense to use entry_points even if you don't need Windows compatibility because it generates the correct shebang for you that points to a specific python interpreter (where generic #! /usr/bin/env python would be the wrong thing).
If the script is meant to be executed from the command line, the .py extension doesn't actually do anything for you. The script will be executed using the Python interpreter under two circumstances:
You explicity said to do so at the command line: $ python nameofyourscript
You explicity said to do so by including a shebang at the top of the script pointing to Python. The preferred version of that is #!/usr/bin/env python.
By including a shebang in each of your scripts, you can name the file anything you want.
Without doing one of these things, the script will be executed as a normal script meant for whatever shell you are using.

How to run a Python script portably without specifying its full path

Is there a portable way to run a python script from a shell without writing its full path?
For example in Linux, I would like while in my home directory
cd ~
to be able to run a python script called run.py that is in say, ~/long/path/to/run.py, but I want to run it by simply typing
python run.py
instead of
python ~/long/path/to/run.py
I would hope for some kind of search path list that contains several directories just like the PATH variable, so that python run.py runs the first run.py it encounters in one of the directories.
I have considered turning run.py into an executable and adding its directory the system PATH variable, but could not find a portable way of making a python script executable.
EDIT
One year later after asking it, I am a bit less noob, and I see that my question was not very clear and did not make much sense, so after a question upvote I'll clarify some things.
1) Portable.
When I asked this I said portable. However what portable means is not clear in this case, and I did not give much emphasis to it.
the platforms: should work on POSIX (Linux, MacOS, etc.) and Windows
this still does not make much sense since windows uses cmd.exe, and POSIX uses sh, so each one could run the commands with a different syntax. So let's say that the most portable thing possible would be to feed the same input to both sh and cmd.exe, running the python script in both cases. In this case, you could run the same command from an ANSI C system function, which uses sh on POSIX and cmd on Windows. ANSI C being one of the few things that is common to Windows and POSIX, the question makes some sense in that case.
2) Executable
Next, the phrase turning run.py into an executable, is not very clear. By that I was talking about the Linux strategy of chmod +x run.py, add a shebang #!/usr/bin/env python, and adding its directory the system add ~/long/path/to/ the PATH enviroment variable. But then this won't work for windows because windows does not support an executable file metadata property like Linux and because /usr/bin/env does not necessarily exist in Windows.
3) Extension
Finally, in my head I was hoping for a solution that does not specify what kind of file run is, so that if someday we decide to make it, say, a perl file, no interfaces would change.
Therefore, writing run.py would be bad because it would specify the filetype; it would be better to be able to write just run
If the directory containing run.py is on the module search path (for example, PYTHONPATH environment variable), you should be able to run it like this:
python -m run
Here is the documentation on the -m command line option:
-m module-name
Searches sys.path for the named module and runs the corresponding .py file as a script.
You can make a python script executable by adding
#!/usr/bin/env python
to the beginning of the file, and making it executable with chmod +x.
Answer after the clarification edit
I prefer the following approach to the one suggested by #F.J. because it does not require users to specify the file type. Please note that this was not specified in the original question, so his answer to the original question was correct.
Lets call the file pytest.py to avoid conflicts with a possible existing run program.
On POSIX (MacOs, linux) do what #Petr said, which is based on what #alberge said:
chmod +x
add shebang #!/usr/bin/env python
create a directory and add it to path. Usual locations on Linux are: ~/bin/ for a single user, /usr/local/bin/ for all users
symlink (cp -s) the file under your PATH with basename pytest instead of pytest.py
On windows:
create a dir and add it to PATH. AFAIK, there is no conventional place for that, so why not C:\bin\ and ~\bin\?
add .PY to the PATHEXT environment variable so that Windows will recognize files with python extension as runnable files without requiring you to type the extension
associate python files with the python.exe interpreter (Windows Explorer > right click > check "Always use the selected program"). There is an option on the python installer that does this for you.
symlink pytest with extension into the dir under PATH (using Link Shell Extension from Windows Explorer or mklink name dest from cmd )
Now system( "pytest" ); should work in both systems ( sh under Linux, cmd under Windows )
Make python file executable (as "alberge" stated above)
Create some directory and put this directory into your PATH variable
In this directory, create links to your python scripts

How to write a script (for Windows XP) to run a python program?

Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas?
From python.org:
On Windows systems, there is no
notion of an “executable mode”. The
Python installer automatically
associates .py files with python.exe
so that a double-click on a Python
file will run it as a script. The
extension can also be .pyw, in that
case, the console window that normally
appears is suppressed.
Also from python.org:
On Windows 2000, the standard Python
installer already associates the .py
extension with a file type
(Python.File) and gives that file type
an open command that runs the
interpreter (D:\Program
Files\Python\python.exe "%1" %*). This
is enough to make scripts executable
from the command prompt as ‘foo.py’.
If you’d rather be able to execute the
script by simple typing ‘foo’ with no
extension you need to add .py to the
PATHEXT environment variable.
Try using a batch file (.bat).
Type in whatever commands you want to execute in the proper order, in notepad, such as:
python program.py
Save the file as iHateTyping.bat
Open the command prompt using Run.
Go to the directory where you saved the file using cd.
Type in:
iHateTyping.bat
& you're done.
I encourage you to read more about batch files in the link highlighted above.
Press Ctrl+R, then type python.py to run your Python script.
Use py2exe to create a portable windows executable file.

Categories