How to Run an Entire Script Again in Python

three. Execute a Script

By Bernd Klein. Last modified: 01 Feb 2022.

So far we accept played around with Python commands in the Python shell. We desire to write now our first serious Python program. You will hardly find whatsoever beginner's textbook on programming, which doesn't start with the "well-nigh mandatory" "Hello World" programme, i.e. a program which prints the string "Hello Globe". We start a Python interactive shell in a terminal with the command "python". Information technology might be necessary to employ "python3" to get a Python3 shell:

          $ python3 (base)            [email protected]:~$ python Python iii.7.1 (default, Dec fourteen 2018, 19:28:38)  [GCC seven.iii.0] :: Anaconda, Inc. on linux Type "aid", "copyright", "credits" or "license" for more data. >>> print("Hello World!") Hello Globe! >>>        

But, every bit we said at the starting time, we want to write a "serious" program now, i.e. a programme which resides in a file. This manner, we tin can use a plan over and over again without having to type it in again. Some may like to call such a piddling program "script". We will use a slight variation of the "Hullo World" theme. We have to include our impress function into a file. To salve and edit our programme in a file we need an editor. There are lots of editors, but you should choose 1, which supports syntax highlighting and indentation. For Linux y'all tin use vi, vim, emacs, geany, gedit and umpteen others. The Emacs works for Windows also, only Notepad++ may be the ameliorate pick in many cases. Of course, y'all can likewise use an IDE (Integrated Development Environment) like PyCharm or Spyder for this purpose.

Then, after you have institute the editor or the IDE of your option, yous are ready to develop your mini programme, i.e.

                            impress              (              "My start elementary Python script!"              )            

OUTPUT:

My first simple Python script!            

and relieve it equally my_first_simple_program.py. The suffix .py is non really necessary for Linux but information technology's practiced to use it since the extension is essential, if you want to write modules.

Kickoff a Python programme

Let's presume our script is in a subdirectory under the dwelling directory of the user monty:

                      [e-mail protected]:~$ cd python            [email protected]:~/python$ python my_first_simple_program.py  My first simple Python script!            [electronic mail protected]:~/python$        

Information technology can be started in a Command Prompt in Windows every bit well (start -> All Programs -> Accessories -> Command Prompt). You may observe that we called our little program "hi.py" and not my_first_simple_program.py:

Command Prompt

Starting a Python Script nether Windows

Python Internals

Most probably you take read somewhere that the Python linguistic communication is an interpreted programming or a script language. The truth is: Python is both an interpreted and a compiled linguistic communication. Merely calling Python a compiled language would exist misleading. (At the end of this affiliate, you lot will find the definitions for Compilers and Interpreters, in instance you are not already familiar with the concepts!) People would assume that the compiler translates the Python lawmaking into auto language. Python code is translated into intermediate code, which has to be executed by a virtual machine, known every bit the PVM, the Python Virtual Motorcar. This is a like arroyo to the one taken by Java. There is fifty-fifty a way of translating Python programs into Java byte lawmaking for the Coffee Virtual Machine (JVM). This tin can be achieved with Jython.

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 y'all shouldn't carp, because "Python" is already doing the thinking for you, i.e. it takes the necessary steps automatically.

For whatever reason you want to compile a python plan manually? No problem. Information technology can be washed with the module py_compile, either using the interpreter beat

                            import              py_compile              py_compile              .              compile              (              'my_first_simple_program.py'              )            

OUTPUT:

'__pycache__/my_first_simple_program.cpython-37.pyc'

or using the following command at the shell prompt

          python -grand py_compile my_first_simple_program.py        

Either way, you lot may detect two things: first, there will be a new subdirectory "__pycache__", if it doesn't already exist. You lot will find a file "my_first_simple_script.cpython-34.pyc" in this subdirectory. This is the compiled version of our file in byte lawmaking.

You can likewise automatically compile all Python files using the compileall module. Y'all can do it from the shell prompt past running compileall.py and providing the path of the directory containing the Python files to compile:

                      [email protected]:~/python$ python -m compileall . Listing . ...        

But equally we accept said, you don't have to and shouldn't bother nearly compiling Python code. The compilation is hidden from the user for a adept reason. Some newbies wonder sometimes where these ominous files with the .pyc suffix might come from. If Python has write-access for the directory where the Python program resides, it volition store the compiled byte lawmaking in a file that ends with a .pyc suffix. If Python has no write admission, the program will piece of work anyway. The byte code volition be produced but discarded when the program exits. Whenever a Python program is called, Python will check, if a compiled version with the .pyc suffix exists. This file has to exist newer than the file with the .py suffix. If such a file exists, Python will load the byte code, which will speed upward the outset upward fourth dimension of the script. If there is no byte code version, Python will create the byte code earlier it starts the execution of the program. Execution of a Python program ways execution of the byte code on the Python.

Source Code to Byte Code

Virtual Machine (PVM).

Compilation of a Python script

Every fourth dimension a Python script is executed, a byte code is created. If a Python script is imported as a module, the byte code will exist stored in the corresponding .pyc file. Then, the following will not create a byte code file:

                      [email protected]:~/python$ python my_first_simple_program.py My offset uncomplicated Python script!            [email protected]:~/python$        

The import in the following Python2 session volition create a byte code file with the name "my_first_simple_program.pyc":

                      [email protected]:~/tmp$ ls  my_first_simple_program.py            [email protected]:~/tmp$ python Python 2.six.five (r265:79063, April 16 2010, thirteen:57:41)  [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import my_first_simple_script My beginning unproblematic Python script! >>> leave()            [electronic mail protected]:~/tmp$ ls my_first_simple_program.py  my_first_simple_program.pyc            [e-mail protected]:~/tmp$        

Live Python preparation

instructor-led training course

Upcoming online Courses

Enrol here

Runnable scripts under Linux

This chapter can be skipped by Windows users. Don't worry! It is non essential!

And then far, we have started our Python scripts with

          python3 my_file.py        

on the bash command line. A Python script tin can as well be started like any other script nether Linux, e.g. Bash scripts. 2 steps are necessary for this purpose: the shebang line #!/usr/bin/env python3 has to be added equally the offset line of your Python code file. Alternatively, this line can exist #!/usr/bin/python3, if this is the location of your Python interpreter. Instead using env every bit 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 besides suffers from the same problem: The path to env may besides be unlike on a per-auto footing. The file has to exist made executable: The command "chmod +x scriptname" has to be executed on a Linux shell, due east.g. fustigate. "chmod 755 scriptname" can too be used to brand your file executable. In our instance:

                      $ chmod +10 my_first_simple_program.py        

Nosotros illustrate this in a bash session:

                      [email protected]:~$ more my_first_simple_script.py  #!/usr/bin/env python3 print("My first simple Python script!")            [email protected]:~$ ls -ltr my_first_simple_script.py  -rw-r--r-- 1 bernd bernd 63 Nov  4 21:17 my_first_simple_script.py            [email protected]:~$ chmod +ten my_first_simple_script.py            [email protected]:~$ ls -ltr my_first_simple_script.py  -rwxr-xr-10 i bernd bernd 63 November  iv 21:17 my_first_simple_script.py            [email protected]:~$ ./my_first_simple_script.py  My first elementary Python script!        

Differences between Compilers and Interpreters

Compiler

Definition: a compiler is a calculator program that transforms (translates) source code of a programming language (the source language) into another computer language (the target language). In most cases compilers are used to transform source lawmaking into executable program, i.e. they translate code from loftier-level programming languages into depression (or lower) level languages, more often than not assembly or car lawmaking.

Interpreter

Definition: an interpreter is a computer programme that executes instructions written in a programming language. It tin can either execute the source lawmaking directly or translate the source code in a first footstep into a more efficient representation and execute this code.

Live Python preparation

instructor-led training course

Upcoming online Courses

Enrol hither

beckthavere49.blogspot.com

Source: https://python-course.eu/python-tutorial/execute-a-script.php

0 Response to "How to Run an Entire Script Again in Python"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel