运行一个Python脚本,回显所执行的命令
考虑下面的脚本,我们把它保存到一个文件 myscript.py。
print("Hello")
a = 4
print(f"{a=}")
我想在控制台中运行它,输出大致会是这样的:
> print("Hello")
Hello
> a = 4
> print(f"{a=}")
a=4
也就是说,一次执行一行,输出被打印出来,然后再进入下一行。
如果我只是把文件的内容复制过来,打开控制台(Windows控制台或WezTerm),把它们粘贴到控制台里,整段脚本都会被粘贴下来(带着一个不会运行的回车符),然后当我按两次回车时,整段脚本就会被执行。因此,我先得到整段源代码,随后是控制台输出。
我想以这种方式运行它,因为这是我的一个库的示例,我想把输出粘贴到该库的README中。
解决方案
我觉得这是一个有趣的问题,我写了一个脚本来实现。给你看看:
import argparse
import ast
import code
import pathlib
# Create parser and get passed script path
parser = argparse.ArgumentParser("line-by-line")
parser.add_argument(
"script_path",
type=pathlib.Path,
help="path to the script to run line-by-line",
)
args = parser.parse_args()
# Open script and get its content
with open(args.script_path, "r") as script_file:
script = script_file.read()
# Check that the script is a valid python file (Optional)
ast.parse(script)
# Create an interactive console to run the script
console = code.InteractiveConsole()
# Run file in the console, and print lines
for line in script.split('\n'):
if line:
print((' ' if console.buffer else '>>> ') + line)
console.push(line)
# Add an empty line (Optional)
if not console.buffer:
print('')
用法:
> python -m <the script name> -h
usage: line-by-line [-h] script_path
positional arguments:
script_path path to the script to run line-by-line
options:
-h, --help show this help message and exit
把 <the script name> 替换为你在文件系统中为该脚本取的实际名称。
测试文件 aaa.py:
print("Hello")
a = 4
print(f"{a=}")
for i in range(5):
print(i)
print(i)
输出:
> python -m <the script name> aaa.py
>>> print("Hello")
Hello
>>> a = 4
>>> print(f"{a=}")
a=4
>>> for i in range(5):
print(str(i))
0
1
2
3
4
>>> print(i)
4
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。