我想知道是否可以将 python 脚本的输入和输出重定向到一个文件,以便它们交错。本质上说我有以下代码:
x = 1
print("hello, world")
print(x)
x = 2
print(x)
def myfun(Val):
return(Val+1)
myfun(7)
我希望在输出文件中显示以下内容
x = 1
print("hello, world")
"hello, world"
print(x)
1
x = 2
print(x)
2
def myfun(Val):
return(Val+1)
myfun(7)
8
我已经看过的内容包括:
简单文件重定向
python myfile.py>output.log
但这不会捕获输入跟踪模块
python -m trace myfile.py
但是,这会显示太多信息并导致运行时膨胀。我找不到任何明显的方法将其限制为顶级代码(不是每个模块和函数调用)Jupyter 笔记本 - 我很欣赏它们可以清楚地显示输入和输出,但是我真的想将其保留为带有基本 ascii python 文件的命令行可执行脚本。
理想情况下,我希望找到某种具有重定向功能的 bash 魔法、Python 命令行选项或能够处理此问题的通用 Python 模块,但到目前为止还没有运气:(
编辑:
作为进一步澄清的示例,本质上我正在尝试从 R 重新创建以下功能。假设我们的 R 程序 myprog.R
为:
myfun <- function(x){
x + 1
}
y <- myfun(7)
print("hello,world!")
print(y)
y + 1
然后从命令行运行R CMD BATCH myprog.R
生成文件myprog.Rout
,如下所示
myfun <- function(x){
x + 1
}
y <- myfun(7)
print("hello,world!")
[1] "hello,world!"
print(y)
[1] 8
y + 1
[1] 9
最佳答案
[编辑]这是一个非常有限的脚本,不幸的是,如果您的代码变得更复杂(意味着语句跨越多行),就像拥有一个函数一样简单,它会立即中断。
对于非常简单的示例用例,您可以使用中间脚本,如下所示(假设文件名 rt.py):
import sys
in_file = sys.argv[1]
with open(in_file) as script:
for line in script:
line = line.strip()
if line:
# Option to visually separate it by using repr
# print(repr(line))
print(line)
# Another optional use a prefix
# print(">>>", end="")
exec(line)
现在您可以将现有脚本传递给它
python rt.py somescript.py
增强此功能以根据缩进准备脚本并非不可能,但这可能不值得,我希望存在我不知道的其他解决方案。
关于python - 如何在输出旁边显示 python 输入代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708380/