Question: I would like to understand the basics of how to write and execute a python program on Linux OS. Can you explain it with a simple example?
Answer: In this article, let us review very quickly how to write a basic Hello World python program and execute *.py program on Linux or Unix OS.
1. Write a Hello World Python Program
Create helloworld.py program as shown below.
$ vim helloworld.py #!/usr/bin/python # Hello world python program print "Hello World!";
2. Verify Python Interpreter Availability
Make sure python interpreter is installed on your system as shown below.
$ whereis python python: /usr/bin/python /usr/bin/python2.5 /usr/bin/python2.6 /etc/python /etc/python2.5 /etc/python2.6 /usr/lib/python2.4 /usr/lib/python3.0 /usr/lib/python2.5 /usr/lib/python2.6 /usr/local/lib/python2.5 /usr/local/lib/python2.6 /usr/include/python2.5 /usr/include/python2.6 /usr/share/python /usr/share/man/man1/python.1.gz $ which python /usr/bin/python
3. Execute Python Program
You can either execute using “python helloworld.py” or “./helloworld.py”.
$ python helloworld.py Hello World! ( or ) $ chmod u+x helloworld.py $ ./helloworld.py Hello World!
Note: As python is an interpreted language, you don’t have the compilation step similar to the C program.
4. Python one liner
You can also execute python from the command line as shown below. This will print Hello World!.
$ python -c 'print "Hello World!"'