python-3.x - 从 python 脚本与 python REPL 交互
问题描述
我想找到(或制作)一个 python 脚本,它逐行读取不同的 python 脚本并打印执行的命令和之后的输出。
假设您有一个 python 脚本,testfile.py
如下所示:
print("Hello world")
for i in range(3):
print(f"i is: {i}")
现在,我想要一个不同的 python 脚本来解析testfile.py
并输出以下内容:
print("Hello world")
## Hello world
for i in range(3):
print(f"i is: {i}")
## i is: 0
## i is: 1
## i is: 2
非常感谢对现有软件或如何实现这一目标的新代码的任何建议!
尝试/概念代码:
ipython
从 python运行:
第一个想法是使用以下命令从 python 运行 ipython subprocess
:
import subprocess
import re
try:
proc = subprocess.Popen(args=["ipython", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
# Delimiter to know when to stop reading
OUTPUT_DELIMITER = ":::EOL:::"
# Variable to contain the entire interaction:
output_string = ""
# Open testfile.py
with open("testfile.py") as file_:
for line in file_:
# Read command
cmd = line.rstrip()
# Add the command to the output string
output_string += cmd + "\n"
proc.stdin.write(f"{cmd}\n")
# Print the delimiter so we know when to end:
proc.stdin.write('print("{}")\n'.format(OUTPUT_DELIMITER))
proc.stdin.flush()
# Start reading output from ipython
while True:
thisoutput = proc.stdout.readline()
thisoutput = thisoutput.rstrip()
# Now check if it's the delimiter
if thisoutput.find(OUTPUT_DELIMITER) >= 0:
break
output_string += thisoutput + "\n"
except Exception as e:
proc.stdout.close()
proc.stdin.close()
raise
proc.stdout.close()
proc.stdin.close()
print("-" * 4 + "START OUTPUT" + "-" * 4)
print(output_string)
print("-" * 4 + "END OUTPUT" + "-" * 4)
在这种方法中,问题变成了缩进块,就像for
循环一样。理想情况下,这样的事情只使用plain python
(而不是ipython
)。
解决方案
这不完全是你想要的,但它很接近。trace
模块做了一些非常相似的事情。
so.py:
print("Hello world")
for i in range(3):
print(f"i is: {i}")
python -m trace --trace so.py
--- modulename: so, funcname: <module>
so.py(1): print("Hello world")
Hello world
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 0
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 1
so.py(3): for i in range(3):
so.py(4): print(f"i is: {i}")
i is: 2
so.py(3): for i in range(3):
推荐阅读
- java - 不支持的类文件主要版本 58
- c# - 如何解决返回从协议构建的抽象类的 iOS 绑定解决方案接口属性
- tensorflow - 如何修改 ImageDataGenerator 以处理 csv 数据
- python - 使用子进程模块运行linux命令
- python - 提交按钮在使用crispy的django表单中不起作用
- node.js - 使用 Instagram Graph API 拉取创作者/公众账号的信息
- powershell - 将 .csv 行保存在不同的文件中
- html - 如何对字符串类型的数字进行排序?
- javascript - javascript 闭包是否可以访问它的外部外部函数
- java - 在请求 OkHttp 中发送 JSON