Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Python Tutorial_ Execute a Script

This document is a tutorial on executing Python scripts, starting with the classic 'Hello World' program. It explains how to write, save, and execute Python scripts using various editors and the command line, as well as the differences between scripts and programs. Additionally, it covers the concepts of compiling and interpreting Python code, emphasizing the flexibility of Python as both an interpreted and compiled language.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Tutorial_ Execute a Script

This document is a tutorial on executing Python scripts, starting with the classic 'Hello World' program. It explains how to write, save, and execute Python scripts using various editors and the command line, as well as the differences between scripts and programs. Additionally, it covers the concepts of compiling and interpreting Python code, emphasizing the flexibility of Python as both an interpreted and compiled language.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: Starting with Python: The Interactive Shell


Next Chapter: Indentation

Execute a Python script


So far we have played around with Python commands in the Python shell. We want to write now our first serious Python program. You will hardly find any beginner's textbook on programming, which don't start with Follow Bernd Klein,
the "nearly mandatory" "Hello World" program, i.e. a program which prints the string "Hello World". This looks on the Python shell like this: the author of this
website, at Google+:
$ python3 Bernd Klein on
Python 3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) Google
Tutorial [GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
Bernd Klein on
The Origins of >>> print("Hello World!")
Hello World! Facebook
Python
>>>
Starting with
Python: The But, as we said at the beginning, we want to write a "serious" script now. We use a slight variation of the "Hello World" theme. We have to include our print statement into a file. To save and edit our program in a Search this website:
Interactive Shell file we need an editor. There are lots of editors, but you should choose one, which supports syntax highlighting and indentation. Under Linux you can use vi, vim, emacs, geany, gedit and umpteen others. The
Executing a emacs works under windows as well, but notepad++ may be the better choice in many cases. Go
Script
Indentation So, after you have found the editor of your choice, you can input your mini script, i.e. This topic in German
Data Types and / Deutsche
print("My first simple Python script!")
Variables Übersetzung:
and save it as my_first_simple_script.py. Ausführen von
Operators
The suffix .py is not really necessary under Linux but it's good style to use it. But the extension is essential, if you want to write modules. Python-Code
Sequential Data
Types: Lists and
Python 3
Strings
List
Start a Python script This is a tutorial in
Manipulations
Python3, but this
Shallow and chapter of our course
Let's assume our script is in a subdirectory under the home directory of user monty:
Deep Copy is available in a
Dictionaries monty@python:~$ cd python version for Python
Sets and Frozen monty@python:~/python$ python my_first_simple_script.py 2.x as well: Execute
Sets My first simple Python script! a Script in Python 2.x
monty@python:~/python$
An Extensive
Example Using Book a
Sets It can be started under Windows in a Command prompt (start -> All Programs -> Accessories -> Command Prompt): Dedicated
input via the Course
keyboard
Conditional The goal of this
website is to provide
Statements
educational material,
Loops, while
allowing you to learn
Loop Python on your own.
For Loops Nevertheless, it is
Difference faster and more
between efficient to attend a
interators und "real" Python course
Iterables in a classroom, with
an experienced
Output with Print
trainer. So why not
Formatted output
Python Internals attend one of the live
with string Python courses
modulo and the
Most probably you will have read somewhere that the Python language is an interpreted programming or a script language. The truth is: Python is both an interpreted and a compiled language. But calling Python a
format method compiled language would be misleading. (At the end of this chapter, you will find the definitions for Compilers and Interpreters, if you are not familiar with the concepts!) People would assume that the compiler
Functions translates the Python code into machine language. Python code is translated into intermediate code, which has to be executed by a virtual machine, known as the PVM, the Python virtual machine. This is a similar
Recursion and approach to the one taken by Java. There is even a way of translating Python programs into Java byte code for the Java Virtual Machine (JVM). This can be achieved with Jython.
Recursive
Functions The question is, do I have to compile my Python scripts to make them faster or how can I compile them? The answer is easy: Normally, you don't need to do anything and you shouldn't bother, because "Python" is
Parameter doing the thinking for you, i.e. it takes the necessary steps automatically.
Passing in
For whatever reason you want to compile a python program manually? No problem. It can be done with the module py_compile, either using the interpreter shell
Functions
Namespaces >>> import py_compile
Global and Local >>> py_compile.compile('my_first_simple_script.py')
Variables >>>
in Paris, London,
Decorators Berlin, Munich or
or using the following command at the shell prompt
Memoization with Lake Constance by
Decorators python -m py_compile my_first_simple_script.py Bernd Klein, the
Read and Write author of this
Files Either way, you may notice two things: First, there will be a new subdirectory "__pycache__", if it hasn't already existed. You will find a file "my_first_simple_script.cpython-34.pyc" in this subdirectory. This is the tutorial?
compiled version of our file in byte code.
Modular
Programming
You can also automatically compile all Python files using the compileall module. You can do it from the shell prompt by running compileall.py and providing the path of the directory containing the Python files to
and Modules Onsite Training
compile:
Packages in Courses
Python monty@python:~/python$ python -m compileall .
Listing . ... Let us come to your
Regular
company or institute
Expressions
and train your
Regular employees, as we've
Expressions, But as we have said, you don't have to and shouldn't bother about compiling Python code. The compilation is hidden from the user for a good reason. Some newbies to Python wonder sometimes where these done it many times in
Advanced ominous files with the .pyc suffix might come from. If Python has write-access for the directory where the Python program resides, it will store the compiled byte code in a file that ends with a .pyc suffix. If Python Amsterdam (The
Lambda has no write access, the program will work anyway. The byte code will be produced but discarded when the program exits. Netherlands), Berlin
Operator, Filter, Whenever a Python program is called, Python will check, if there exists a compiled version with the .pyc suffix. This file has to be newer than the file with the .py suffix. If such a file exists, Python will load the byte (Germany), Bern
Reduce and Map code, which will speed up the start up time of the script. If there exists no byte code version, Python will create the byte code before it starts the execution of the program. Execution of a Python program means (Switzerland), Basel
execution of the byte code on the Python Virtual Machine (PVM). (Switzerland), Zurich
List
(Switzerland),
Comprehension
Locarno
Iterators and
(Switzerland), Den
Generators Haag (The Hague),
Exception Hamburg (Germany),
Handling Frankfurt (Germany),
Tests, DocTests, Toronto (Canada),
UnitTests Edmonton (Canada),
Every time a Python script is executed, byte code is created. If a Python script is imported as a module, the byte code will be stored in the corresponding .pyc file. Munich (Germany)
Object Oriented
So the following will not create a byte code file: and many other
Programming
cities. We do training
Class and monty@python:~/python$ python my_first_simple_script.py courses in England,
Instance My first simple Python script!
Switzerland,
Attributes monty@python:~/python$
Liechtenstein,
Properties vs. Austria, Germany,
The import in the following Python2 session will create a byte code file with the name "my_first_simple_script.pyc":
getters and France, Belgium, the
setters monty@python:~/tmp$ ls Netherlands,
Inheritance my_first_simple_script.py Luxembourg, Poland,
monty@python:~/tmp$ python UK, Italy and other
Multiple Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) locations in Europe
Inheritance [GCC 4.4.3] on linux2
and in Canada.
Magic Methods Type "help", "copyright", "credits" or "license" for more information.
and Operator >>> import my_first_simple_script
My first simple Python script! This way you will get
Overloading >>> exit() a perfect training up
OOP, Inheritance monty@python:~/tmp$ ls to your needs and it
Example my_first_simple_script.py my_first_simple_script.pyc will be extremely cost
monty@python:~/tmp$ efficient as well.
Slots
Classes and Contact us so we can
define and find the
Class Creation
best course
Road to
curriculum to meet
Metaclasses your needs, and
Runnable Scripts under Linux
Metaclasses schedule course
Metaclass Use sessions to be held at
This chapter can be skipped by Windows users. Don't worry! It is not essential!
Case: Count your location.
Function Calls So far, we have started our Python scripts with
Abstract Classes
python3 my_file.py Skilled Python
Programmers
on the bash command line.
A Python script can also be started like any other script under Linux, e.g. Bash scripts. Two steps are necessary for this purpose:
You can hire skilled
1. The shebang line #!/usr/bin/env python3 has to be added as the first line of your Python code file. Alternatively, this line can be #!/usr/bin/python3, if this is the location of your Python interpreter. By instead using env Python programmers
Difference as in the first shebang line, the interpreter is searched for and located at the time the script is run. This makes the script more portable. Yet, it also suffers from the same problem: The path to env may also or even a skilled
between a be different on a per-machine basis. team of Python
Script and a 2. The file has to be made executable: The command "chmod +x scriptname" has to be executed on a Linux shell, e.g. bash. "chmod 755 scriptname" can also be used to make your file executable. In our developers to work
Program example: exclusively on your
project. Contact us, if
$ chmod +x my_first_simple_script.py you want more
There is a fluent
information.
passage between
We illustrate this in a bash session:
scripts and programs.
There is a kind of Quote of the
bernd@saturn: $ more my_first_simple_script.py
nether land, where Day:
#!/usr/bin/env python3
the result of the print("My first simple Python script!")
programming can be bernd@saturn: $ ls -l my_first_simple_script.py "I think the special
correctly called a -rw-rw-r-- 1 bernd bernd 40 Feb 4 09:32 my_first_simple_script.py thing about Python is
script or a program. bernd@saturn: $ chmod +x my_first_simple_script.py that it's a writers'
bernd@saturn: $ ls -l my_first_simple_script.py commune. The
But there are works
-rwxrwxr-x 1 bernd bernd 40 Feb 4 09:32 my_first_simple_script.py
which are clearly writers are in charge.
My first simple Python script!
programs and others The writers decide
which are definitely what the material is."
scripts and can't be (Eric Idle )
called programs.
Differences between Compilers and Interpreters
Script can mean
womething written by
hand and a particular Compiler
orthography or Data Protection
writing system. The Declaration
Definition: A compiler is a computer program that transforms (translates) source code of a programming language (the source language) into another computer language (the target language). In most cases
term script is also
compilers are used to transform source code into executable program, i.e. they translate code from high-level programming languages into low (or lower) level languages, mostly assembly or machine code.
used for a written Data Protection
version of a play, film Declaration
or some other work Interpreter
of dramatic
composition. Definition: An interpreter is a computer program that executes instructions written in a programming language. It can either

In the past, we could execute the source code directly or


say a program is translates the source code in a first step into a more efficient representation and executes this code
compiled (C, C++)
and a script is Previous Chapter: Starting with Python: The Interactive Shell
interpreted (like bash Next Chapter: Indentation
scripts). But
nowadays this is not
a clear dividing line
anymore. Modern
languages like Python
and Java are
interpreted and
compiled without the
necessity of the strict
edit-compile-test-
debug cycle. Of
course, compilation
in Python and Java
doesn't mean that
they are compiled
into machine code.
They are compiled
into pseudo or virtual
machine code, which
is byte code close to
machine code.

A script is something
comparatively small,
but you would never
call the "Hello World"
program written in C
a script, because it is
compiled. But as we
said before: With
languages like Python
the traditional
difference is
dissolving. You can
start writing a small
Python script. But
while your script is
getting larger and
maturing, you will
pass through the no-
man's-land, where
your work is both a
script and a program,
but finally it will
reach a stage, where
it is not a script
anymore but clearly a
program.

Supported by:

Courses and
Seminars for Linux
and Python

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like