杰瑞科技汇

Python interpreter是什么?如何运行Python代码?

Of course! Here is a comprehensive guide to the Python interpreter, from the basic concept to practical examples and advanced usage.

Python interpreter是什么?如何运行Python代码?-图1
(图片来源网络,侵删)

What is a Python Interpreter?

At its core, a Python interpreter is a program that reads and executes Python code. It acts as a bridge between your human-readable Python scripts and the computer's processor, which only understands binary (0s and 1s).

Think of it like a translator:

  1. You write a command in Python (e.g., print("Hello")).
  2. The interpreter reads this command.
  3. It translates the command into a set of low-level instructions that the computer's CPU can execute.
  4. The computer performs the action (displays "Hello" on the screen).

Python is often called an interpreted language because this translation and execution happen line by line, or even statement by statement, at runtime. This is different from a compiled language (like C++ or Rust), where the entire code is translated to machine code before it's run.

How Does It Work? (The Simple Version)

The process of running Python code involves two main steps, often handled by the interpreter together:

Python interpreter是什么?如何运行Python代码?-图2
(图片来源网络,侵删)
  1. Parsing: The interpreter reads your source code and checks its syntax. It breaks the code into small pieces called "tokens" and builds a structure (an Abstract Syntax Tree or AST) to understand the relationships between the tokens.
  2. Execution: The interpreter walks through the AST and executes the commands. This is where the translation to machine-specific instructions happens.

Fun Fact: The standard Python interpreter, called CPython, is itself written in C. It compiles your Python code into an intermediate form called bytecode (a .pyc file). This bytecode is then executed by a "virtual machine," which is part of the interpreter. This compilation step makes execution faster than re-parsing the source code every time.


How to Use the Python Interpreter

There are three primary ways you'll interact with the Python interpreter.

The Interactive Mode (REPL)

This is the quickest way to experiment with Python. The term REPL stands for Read, Evaluate, Print, Loop.

  • Read: The interpreter reads your command.
  • Evaluate: It evaluates the command.
  • Print: It prints the result of the evaluation.
  • Loop: It waits for your next command.

How to start it: Open your terminal or command prompt and type python or python3 and press Enter.

Python interpreter是什么?如何运行Python代码?-图3
(图片来源网络,侵删)
# On macOS/Linux
$ python3
# On Windows
> python

You'll see a >>> prompt, which means the interpreter is ready for your input.

Example:

>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
5
>>> name = "Alice"
>>> print(f"Hello, {name}")
Hello, Alice
>>> # To exit, type exit() or press Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows)
>>> exit()
$

This is perfect for quick calculations, testing small snippets of code, or learning Python syntax.

Running a Python Script File

This is the most common way to use Python for building applications. You write your code in a file (e.g., my_app.py) and tell the interpreter to execute the entire file.

Step 1: Create a file. Create a file named my_app.py and add the following code:

# my_app.py
print("This is a script.")
user_name = input("What is your name? ")
print(f"Hello, {user_name}! Welcome to the script.")

Step 2: Run the file from your terminal. Navigate to the directory where you saved the file and run it using the interpreter.

$ python3 my_app.py

Output:

This is a script.
What is your name? Bob
Hello, Bob! Welcome to the script.

The interpreter reads the file from top to bottom and executes each line.

Using Shebang for Direct Execution (Linux/macOS)

On Unix-like systems (Linux, macOS), you can make a Python script executable directly, just like any other program (e.g., ls, git).

Step 1: Add a "shebang" line. The shebang line tells the operating system which interpreter to use. It must be the very first line of the file.

#!/usr/bin/env python3
# my_app.py
print("This script is now executable!")
user_name = input("What is your name? ")
print(f"Hello, {user_name}!")

Step 2: Make the file executable. In your terminal, use the chmod command.

$ chmod +x my_app.py

Step 3: Run the script directly. Now you can run the script without typing python3 first.

$ ./my_app.py

Note: You may need to run chmod +x on the file every time you edit it if your editor changes the file permissions.


Common Interpreter Commands and Flags

You can use flags when you call the interpreter from the command line to change its behavior.

Flag/Command Description Example
python3 script.py Standard Execution: Runs the specified Python script. python3 my_app.py
-c <command> Execute Command: Runs a single string of Python code. python3 -c "print('Hello from a command!')"
-m <module> Run Module: Runs a module as a script. Very useful for packages. python3 -m pip install requests
--version Show Version: Prints the Python interpreter's version. python3 --version
-i Run Interactively: Runs a script and then drops into the interactive mode. Great for debugging. python3 -i my_app.py
--help Show Help: Displays a list of all available command-line options. python3 --help

Different Python Interpreters

The "Python interpreter" isn't just one program. There are several different implementations, each with its own strengths.

Interpreter Description Best For...
CPython The standard, official interpreter, written in C. Most use cases. This is what you get when you install Python from python.org. It's the reference implementation.
PyPy An alternative interpreter written in a restricted version of Python (RPython). Performance. It uses a Just-In-Time (JIT) compiler, which can make it significantly faster for long-running applications, especially with heavy computation.
Jython An interpreter that runs on the Java Virtual Machine (JVM). Integration with Java. Allows you to use Python libraries and call Java classes from within Python.
IronPython An interpreter that runs on the .NET (and now Mono) framework. Integration with C#/.NET. Allows you to use Python within the .NET ecosystem.
MicroPython A lean and efficient implementation of Python 3. Microcontrollers and embedded systems (e.g., Raspberry Pi Pico, ESP32). It has a small footprint and is optimized for limited resources.
BeeWare A suite of tools and libraries, including a Python interpreter (Toga), to build native apps. Building native user interfaces for desktop, mobile, and web from Python code.

For most developers starting out, you will be using CPython. It's the most common, has the most support, and is what you'll find in almost online tutorials and courses.

分享:
扫描分享到社交APP
上一篇
下一篇