Python3 解释器
交互式编程与脚本式编程两种运行方式、REPL 常用技巧与退出方法。
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 resultexit()/quit()/ Ctrl-D leaves the REPLhelp(obj)opens the built-in help pagerdir(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: 0On 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.交互式编程
在终端直接输入 python(或 python3)进入交互式解释器,出现 >>> 提示符后逐行输入,回车立即得到结果。它不会保存代码,适合验证语法和探索库。
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]_保存上一次的计算结果exit()/quit()/ Ctrl-D 退出交互环境help(obj)打开内置帮助dir(obj)列出对象属性
脚本式编程
把代码写进 .py 文件,用 python 文件名.py 执行。这是真实项目的方式:代码可版本管理、可复用、可传参。文件里可以没有输出语句,也可以有。
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: 0Windows 上若
python 命令不可用,试试 py 启动器;macOS / Linux 上通常同时存在 python3。用 python -m 模块名 可以按模块方式运行,例如 python -m http.server。