for-loop on cmd-line

Dave Angel d at davea.name
Thu Oct 11 07:54:33 EDT 2012


On 10/11/2012 07:24 AM, Gisle Vanem wrote:
> Hello list. I'm a newbie when it comes to Python.
>
> I'm trying to turn this:
>
> def print_sys_path():
>    i = 0
>    for p in sys.path:
>      print ('sys.path[%2d]: %s' % (i, p))
>      i += 1
>
> into a one-line python command (in a .bat file):
>
>  python -c "import sys,os; i=0; for p in sys.path:
> print('sys.path[%%2d]: %%s' %% (i, p)); i+=1"
>
> But:
>  File "<string>", line 1
>    import sys,os; i=0; for p in sys.path: print('sys.path[%2d]: %s' %
> (i, p)); i+=1
>                          ^
> SyntaxError: invalid syntax
>
> The caret is on the 'for'. What's the problem?

>
> --gv

it has nothing to do with being on a command line.  You're using
semicolon to combine several statements, and there are restrictions on
what can be combined that way.  One restriction is the looping
constructs, for, if, while.

Try experimenting with a standard program, to see what can be combined
and what cannot.

You can do it easily enough with a list comprehension.  Let us know if
you can't work that out.

By the way, much cleaner than defining your own counting variable is to
use enumerate().

Any reason why you don't just make a one-file python script, and run
that instead of your one line batch file?  Or is this line one of many
in the batch file?

-- 

DaveA





More information about the Python-list mailing list