How to run the python code after it is written, and how to run it after python programming

This article will tell you how to run a program written in python to the desktop, and how to run a program written in python. I hope it will be helpful to you. Don’t forget to bookmark this site.

In terms of implementation, python is a software package called an interpreter. An interpreter is a program that makes other programs run . When writing a python program, the Pyhton interpreter will read the program, execute the commands in it, and get the result. In effect, the interpreter is the software logic layer between the code and the computer hardware of the machine. The Python installation package contains at least an interpreter and a set of supporting libraries.

program execution

From a programmer's point of view, a Python program is a text file containing Python statements. By convention, Python files end in .py. This naming scheme is only required when being "imported", but most Python files are named with .py for uniformity.

From the perspective of python, the internal execution process of python: the first step is to compile into the so-called "bytecode", and then forward it to the so-called "virtual machine" (PVM).

Bytecode is a low-level, platform-independent representation, and in a nutshell, Python improves execution speed by breaking each of your source statements into a single step to translate into a set of bytecode instructions. If the Python process has write access on the machine, it saves the program's bytecode as a file with a .py extension. In Python 3.2 and later, Python stores .py bytecode in a subdirectory named __pycahe__, which is located in the same path as the source file. Note that source file modifications and Python version changes will trigger compilation of new bytecode files.

Once a program is compiled into bytecode, the bytecode is then sent to be executed by a program commonly known as the Python Virtual Machine (PVM). The PVM is the engine of the Python runtime, which often appears to be part of the Python system, and is the component that actually runs the script.

1 Introduction

Python is an object-oriented scripting language that combines object-oriented support with the role of a full-fledged scripting language.

Python has the following advantages: object-oriented, free, portable, powerful (rich tool set makes python between traditional scripting language and system language, tool set includes dynamic type), mixable (can be written with C\C++ library files), easy to use.

Cpython is one of the three major implementations of the python language, and it is the original and standard implementation. Jpython can be integrated with the java language and is an alternative implementation of the python language. The java class included in Jpython compiles python source code into java bytecode. The third implementation is ironpython , which allows python programs to integrate with .net frameworks and applications written in Mono for Linux.

py2exe (used under windows) can generate a frozen binary file (Frozen Binary) , which can bundle the program's bytecode, PVM, and any python support files required by the program into a single executable binary program.

2. How to run Python programs

Interactive command line mode

The easiest way to run a python program is to enter the program in the python interactive command line, enter python in the command prompt or enter in the "Run" dialog box or start the main window of IDLE, you can open an interactive python session. Press enter to execute immediately. ctrl+z: Exit the python shell window. ctrl+D exits the IDLE GUI and the Python session under the UNIX system.

>>>print('hello world!')

>>>2**8

Explanation: In python3, print is a function call, but in python2 it is not. Since interactively automatically prints the result of the entered expression, typing "print" is often unnecessary in this prompt mode.

Function: Used to experience the language and test the program; Disadvantage: Enter the code in interactive mode, it will disappear immediately after execution, and will not be saved in a file, so in order to re-run, you have to start from scratch. At this time, in order to save the program, code needs to be written in a file, and such a file is usually called a module.

Note the following when using the interactive prompt mode:

  • It is not necessary to enter the complete print statement in interactive mode, but the print statement in the file is necessary.
  • Indentation is not required in interactive prompt mode, otherwise a "SyntaxError" message will appear.
  • Watch out for prompts , transformations, and compound statements (multiline statements). Having to press enter twice to run a compound statement creates an extra blank line. Only one statement can be run at a time: you must press enter twice to run a loop or other multi-line statement. This means that multiple lines of code cannot be copied and pasted interactively unless the code contains blank lines after each compound statement.
  • In the shell command line, the second line of a multi-line statement needs to be indented manually, but in IDLE, it is automatically indented.

The use of shortcut keys in the command line of IDLE: ALT+P: Roll back the previous command; Alt+N: Find the command from the beginning

In the windows interactive dialog environment, you can use the arrow keys to recall used commands

>>>for x in 'spam':
...    print(x)
...

python script

Open with a text editor, such as IDLE editor, Notepad, etc. After the # symbol is a comment, which can be on a line by itself or placed on the right side of the code.

Method 1 : IDLE is a GUI that can edit, run, browse and debug python programs. It is a script idle.py in python3.X\Lib\idlelib. After opening IDLE, click File to select new file, and an editor window will appear. Enter the code and save it as new3.py. Then click Run to select Run Module, and the result will appear in the shell window. Or click File to choose to open an existing file

# 导入模块
import sys
print(sys.platform)
print(2**100)
x='Spam!'
print(x*8)

                    

Method 2: System command line: Use notepad to edit the .py file, press shift + right mouse button in the current directory, choose to enter powershell, and enter python xx.py. If you want to generate a pyc file, you can use the python -m xx command .

  • If your Path doesn't contain a directory for python, and neither python nor your script file is in the directory you're working in, then this uses the full path for both.
  • Use file extensions in system prompt mode, but not when importing, such as import sys.

Method 3 : Click the py file directly, select python.exe as the opening method, and the dos terminal window will flash by, and you can add input() after the code. Limitations: If there is an error before input(), the error message will be displayed in the window, but only briefly, so the input() call will not help.

Note: In window, there is also a method to completely prevent the DOS terminal window from popping up. Files with a pyw extension only display windows built by the script, rather than the default dos window. pyw files are py files that have this special windowing behavior. They are commonly used in the python editor's user interface, and are used with various other techniques to save printed output and errors to files.

Module import and reloading

Module: Every python source file ending with the extension py. Other files can read the contents of a module by importing it. Often larger programs appear in the form of multiple module files, one of which is designed as the main file, or called the top-level file (that is, the file that can run the entire program after startup)

The import operation can only be performed once in the same session. For example, if you enter the python shell window and enter import new3, there will be results. If you import new3 again, there will be no results.

Note: The new3 file must be under the "pythonX.X" or "pythonX.X\Lib\site-packages" path.

About imported search path settings

Tip 1: Add system PYTHONPATH variable: search path for python modules (used to import)

Tip 2: Create a text mypath.pth file under pythonX.X, and enter your own search path

You can also run the file again in the same session. You need to call the reload function available in the importlib standard library module. This function is a built-in function in python2, but not in python3. The from statement can directly copy a name from a module . The reload function loads and runs the latest version of the code of the file. The obtained parameter is the name of a module object that has been loaded (import new3), and the object returned is a python module. , so one more line is displayed.        

reload is non-transferable. Reloading a module will only reload the module, but not any modules imported by the module, so sometimes multiple files must be reloaded.

How to load the attributes in the new4 module file?                                     

Method 1: Load the module as a whole by using an import statement, and use the module name followed by a property name to get it.

>>> import new4
>>> print(new4.theme1)
The Meaning of life
>>>

Method 2: Obtain the variable name from the module file through from

>>> from new4 import theme1
>>> print(theme1)
The Meaning of life
>>>

The difference between the two is that method 1 loads the module as a whole, using object.attribute attribute reference; method 2 from only copies the attributes of the module so that the attributes become direct variables (copies) of the receiver (theme1), breaking the namespace of the module separation, but this at least leads to possible overlap on the copied variables.

Generally speaking, a python program is composed of multiple modules, which are connected together by import statements. Each module file is an independent variable package, that is, a namespace. A module file cannot see the variable names defined by other files unless it is explicitly defined. imports that file formally, so the module file acts as the least naming conflict in the code file . Because each file is a self-contained namespace, variable names in one file cannot conflict with variables in another file, even if they are spelled the same.

                                     

>>> import new4
The Meaning of life patriotism persistence
>>> dir(new4)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'theme1', 'theme2', 'theme3']
>>> 

exec run module file 

Use exec to run module files without importing module functions 

exec(open('xxx.py').read()) is a way to start a file from interactive prompt mode without importing and subsequent reloading, as built-in function calls. The exec call has the same effect as import, but it doesn't technically import the module, and by default it re-runs the file every time exec is called this way. So exec doesn't need to do module reload after file modification, it ignores normal module import logic. The disadvantage is that because the working mechanism of exec is like pasting the code at the calling place, the current variable is in danger of being overwritten like from.

Note: The parameter of open is the file path, the default is in the python3.X folder, the file in any directory can be written as 'D:\\\\programming\\\\python3.8\\\\workplace \\ \\new4.py' form.

Summary: This article mainly introduces the way to use code interactive input to start the code saved in the file in different ways: run in the system command line, import and exec, use GUI like IDLE, etc.

Summary of commonly used shortcut keys for IDLE:

ALT+P: Roll back the previous command; Alt+N: Find the command from the beginning

ctrl+D to exit the IDLE GUI.

ctrl+[: multi-line indentation; ctrl+]: multi-line back

alt+3: multi-line comment

alt+4: cancel multi-line comment

おすすめ

転載: blog.csdn.net/mynote/article/details/132405084