Search code examples
pythonpdbdjango-shell

How to create a single-line script with two for loops, in the debugger, in python 2.7


Creating a single line for loop in the python debugger or django shell is easy:

>>>> for x in (1,2,3,4):print(x);
>>>> for x in Obj.objects.all():something(x);

But how can I get a second for loop in there?

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

I care because it's nice to have up arrow edit of the prior command, when working interactively (this is not an attempt to use single line commands in any other context).

NOTE: the "print" is just an example. In real use I'd iterate objects or perform other programming or debugging tasks such as 'for s in Section.objects.all():for j in s.children():print j'. I am using Python 2.7.


Solution

  • For the times that a list comprehension just won't do

    for x in (1,2,3,4):print x;exec("for y in (5,6):print x,y;")
    

    or

    for s in Section.objects.all():exec("for j in s.children():print j")
    

    Sometimes you can use itertools.product (But there's no way to get the print x) like this

    for x, y in itertools.product((1,2,3,4), (5,6)):print x,y)