Monday, 18 June 2018

How To Run a Python program? And Why Is It A Good Thing?

Isn’t that a question with an obvious answer? Not so much. Answering it takes us to the heart of how Python works.

Write a Windows program in a language such as C#, and the IDE compiles to a self-contained .exe file (as much as any .exe is ‘self-contained’ when it makes calls to all those Windows DLL’s). My reflexes have been developed on languages like that: compile and run.

So my first thought, having got code that worked as it was supposed to, was to make an .exe file. It was then I found out that PyCharm doesn’t compile Python scripts as, say, a C# IDE does. If you really want an .exe file, you have to find a third-party application to compile the scripts and wrap in all the dependencies. The most popular way of doing that is to use Py2Exe. That only works on Python 2.7, and hasn’t been upgraded to handle the 3.x versions of Python. Lesson in there somewhere.

The lesson is this. There are two Pythons. One is the scripting language. The other is a program that runs those scripts. That’s why the command line prompt is ‘python mystuff.py’. It’s telling the Python program to run the Python script in ‘mystuff.py’.

The Python program on Windows converts a .py file into something Windows understands. The Python program on OS X converts the same .py file into something OS X understands. So .py files are portable. mystuff.py will run on any computer with a Python program. (Given Python version compatibility.)

Browsers work in the same way. You download a web page full of all sorts of HTML and other programming junk, and the browser interprets it all in terms the operating system understands and throws the result at the computer to run.

Which means that ‘everyone’ has to have a Python install to use a .py script. Well, okay. Would you expect to be able to ‘run’ an Excel workbook without Excel? You need Excel to be installed.

So how do I run the program? Set up a .bat file with the command line in it, and put that in the Start Menu. Click on it, and it will start up like a ‘real’ .exe program. Which is all I need.

No comments:

Post a Comment