我想实时访问解释器输入和错误以及标准输出.优选地,该信息将被写入文件,以便在输入每个解释器命令之后我可以轮询文件以进行更改.例如,给定一个解释器会话:
>>> 5 * 7
35
>>> print("Hello, world!")
Hello, world!
>>> "Hello, world!"
'Hello, world!'
Run Code Online (Sandbox Code Playgroud)
我想在日志文件中看到以下内容:
> 5 * 7
35
> print("Hello, world!")
Hello, world!
> "Hello, world!"
'Hello, world!'
Run Code Online (Sandbox Code Playgroud)
格式化并不重要; 重要的是我可以在文件中搜索关键词以在会话期间触发交互事件.
到目前为止我学到了什么:
Python的code模块允许我创建一个InteractiveConsole对象,raw_input我可以重新定义该方法以记录到文件,如下所示:
import code
class LoggedConsole(code.InteractiveConsole):
def __init__(self, locals):
super(LoggedConsole, self).__init__(locals)
self.file = open('consolelog.dat', 'a')
def __del__(self):
self.file.close()
def raw_input(self, prompt=""):
data = input(prompt)
self.file.write(data+'\n')
return data
Run Code Online (Sandbox Code Playgroud)
此外,InteractiveConsole使用内置write方法记录错误,我可以重新定义:
def write(self, data):
sys.stderr.write(data)
self.file.write(data+'\n')
Run Code Online (Sandbox Code Playgroud)
我还了解到以下片段将记录所有标准输出:
class Tee(object): …Run Code Online (Sandbox Code Playgroud) 什么是在复杂嵌套结构的嵌套字段上施加条件的最佳方法,如...
{
:aa {:a "a_val",:b "b_val"},
:qq {:abc
{
:x1 {:x "abc",:u "ee"},
:x2 {:y "abc",:i "ee"},
:x3 {:x "abc",:i "ee"}
}
},
:ww {:xyz {
:y1 {:x "abc",:u "ee"},
:y2 {:y "abc",:i "0"},
:y3 {:x "abc",:i "ee"}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想检查"i"部分是否存在并且在aa,qq和ww中的每一个中具有值"0"并且取决于对aa,qq和ww的排除(或执行任何操作).例如,如果"ww"在该位置具有"i"="0",则获得如下的地图
{
:ww {:xyz {
:y1 {:x "abc",:u "ee"},
:y2 {:y "abc",:i "0"},
:y3 {:x "abc",:i "ee"}
}
}
}
Run Code Online (Sandbox Code Playgroud) 我创建了一个尾递归函数来解决优化问题:
def optimize(current_price = 0.1, last_profit = 0.0):
current_profit = profit(current_price)
if (last_profit > current_profit) and (current_profit > 0.0):
return {'best_price': current_price - 0.1, 'best_profit': last_profit}
# print({'best_price': current_price - 0.1, 'best_profit': last_profit})
else:
optimize(current_price + 0.1, current_profit)
def best_price():
optimized = optimize() # optimize() should return a dict,
# allowing optimized['best_price']
# and optimized['best_profit'] to be called
print("Pricing the tickets at ${0} will produce the greatest profit, ${1}.".format(optimized['best_price'], optimized['best_profit']))
Run Code Online (Sandbox Code Playgroud)
该函数正常运行,但它无法返回任何内容.我并不是说第一个if语句永远不会被调用(事实上,当我取消注释打印行时,它将打印正确的结果),但是return语句无法返回字典.
这导致TypeError我试图打电话时optimized['best_price'],如'NoneType' object …