Re: for-loop on cmd-line

Discussion in 'Python' started by Dave Angel, Oct 11, 2012.

  1. Dave Angel

    Dave Angel Guest

    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
    Dave Angel, Oct 11, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Achim Domma (Procoders)

    read input for cmd.Cmd from file

    Achim Domma (Procoders), Jun 3, 2005, in forum: Python
    Replies:
    2
    Views:
    8,027
    Peter Otten
    Jun 3, 2005
  2. Sarir Khamsi

    Interpreter-like help in cmd.Cmd

    Sarir Khamsi, Jun 9, 2005, in forum: Python
    Replies:
    4
    Views:
    348
    Bengt Richter
    Jun 26, 2005
  3. =?ISO-8859-1?Q?Sch=FCle_Daniel?=

    [exec cmd for cmd in cmds]

    =?ISO-8859-1?Q?Sch=FCle_Daniel?=, Mar 8, 2006, in forum: Python
    Replies:
    3
    Views:
    365
    Scott David Daniels
    Mar 8, 2006
  4. Diez B. Roggisch

    pydb remote debugging/cmd.Cmd over socket?

    Diez B. Roggisch, May 28, 2008, in forum: Python
    Replies:
    2
    Views:
    535
    Diez B. Roggisch
    May 29, 2008
  5. Isaac Won
    Replies:
    9
    Views:
    343
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page