如何在调试器中使用python 2.7创建带有两个for循环的单行脚本

Bry*_*yce 2 python django-shell pdb

在python调试器或django shell中创建一行for循环很容易:

>>>> for x in (1,2,3,4):print(x);
>>>> for x in Obj.objects.all():something(x);
Run Code Online (Sandbox Code Playgroud)

但是我怎么能在那里得到第二个for循环呢?

>>>> for x in (1,2,3,4):print x;for y in (5,6):print x,y;
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我很在意,因为在交互式工作时对前一个命令进行向上箭头编辑很好(这不是尝试在任何其他上下文中使用单行命令).

注意:"打印"只是一个例子.在实际使用中,我会迭代对象或执行其他编程或调试任务,例如'for s in Section.objects.all():for s in s.children():print j'.我使用的是Python 2.7.

Joh*_*ooy 6

对于列表理解不会做的时间

for x in (1,2,3,4):print x;exec("for y in (5,6):print x,y;")
Run Code Online (Sandbox Code Playgroud)

要么

for s in Section.objects.all():exec("for j in s.children():print j")
Run Code Online (Sandbox Code Playgroud)

有时你可以使用itertools.product(但没有办法得到print x)像这样

for x, y in itertools.product((1,2,3,4), (5,6)):print x,y)
Run Code Online (Sandbox Code Playgroud)

  • @KaranGoel,用例是你在调试时想要使用向上箭头编辑并重新运行该行.我认为`exec`在这里没问题 (2认同)