Python3 解释器

交互式编程与脚本式编程两种运行方式、REPL 常用技巧与退出方法。

Beginner
Key Points交互式适合试语句、看结果;脚本式适合真实程序。REPL 里 `_` 保存上一次结果,`exit()` 或 Ctrl-D 退出。

交互式编程

Run python (or python3) in a terminal to enter the interactive interpreter. After the >>> prompt, each line executes on Enter. Nothing is saved — perfect for checking syntax and poking at libraries.

Python
import code

session = "1 + 1\nlen('abc')\n_ * 2\n"
out_lines = []
for line in session.strip().splitlines():
    try:
        val = eval(line, {'_': out_lines[-1] if out_lines else None})
        out_lines.append(val)
        print('>>>', line)
        print(val)
    except Exception as e:
        print('>>>', line)
        print(type(e).__name__, e)

print('history:', out_lines)
Output
>>> 1 + 1
2
>>> len('abc')
3
>>> _ * 2
6
history: [2, 3, 6]
  • _ holds the last result
  • exit() / quit() / Ctrl-D leaves the REPL
  • help(obj) opens the built-in help pager
  • dir(obj) lists attributes of an object

脚本式编程

Put code in a .py file and run python file.py. This is how real projects work: version-controllable, reusable, parameterisable. A file may or may not print anything.

Python
import os
import sys
import tempfile
import subprocess

d = tempfile.mkdtemp()
path = os.path.join(d, 'hello.py')
with open(path, 'w', encoding='utf-8') as f:
    f.write("import sys\nprint('hello from script')\nprint('argv:', sys.argv[1:])\n")

r = subprocess.run([sys.executable, path, 'a', 'b'],
                   capture_output=True, text=True)
print(r.stdout.strip())
print('exit code:', r.returncode)
Output
hello from script
argv: ['a', 'b']
exit code: 0
On Windows, if python is missing try the py launcher; on macOS / Linux python3 is usually present. python -m module runs a module directly, e.g. python -m http.server.

Friends & Partners