for-loop on cmd-line

G

Gisle Vanem

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
 
S

suzaku

According to the document (http://docs.python.org/using/cmdline.html#interface-options),
When called with -c command, it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!

So you should replace the semicolon with newline.

BTW, the loop can be simplified using `enumerate` like this:

for i, p in enumerate(sys.path):


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
 
S

suzaku

According to the document (http://docs.python.org/using/cmdline.html#interface-options),
When called with -c command, it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!

So you should replace the semicolon with newline.

BTW, the loop can be simplified using `enumerate` like this:

for i, p in enumerate(sys.path):


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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,154
Members
46,702
Latest member
LukasConde

Latest Threads

Top