Python interpreter call with -c questions and indentation

I'm trying to call Python with the "-c" argument so that I can easily run arbitrary python code, for example: python.exe -c "for idx in range(10): print idx" Now this code works fine, from inside my batch file however, I am having problems when I want to do something more than that.

Consider the following Python code:

 foo = 'bar' for idx in range(10): print idx 

this will give you 0-9 on stdout. However, if I drop it on one line, using semicolons as separators, we get the following:

 foo = 'bar';for idx in range(10): print idx 

and try running it with python.exe -c , it will get a SyntaxError message:

 C:\Python>python.exe -c "foo = 'bar';for idx in range(10): print idx" File "<string>", line 1 foo = 'bar';for idx in range(10): print idx ^ SyntaxError: invalid syntax 

Does anyone know how I can use this without switching to a separate .py file?

I run this from the .cmd batch file using the call method:

 call python.exe -c "blah blah" 

with the same error generated.

+4
source share
2 answers

You need to enter the command line as a multi-line argument. With linux, it is as simple as using the enter key, for example. (note that bash adds the characters > , I did not need to enter them):

 $ python -c "foo = 'bar' > for idx in range(10): > print idx" 

On Windows, however, you need to type the ^ key before you press Enter and leave a blank line to get a newline character, for example. ( More? Added cmd )

 C:\> python.exe -c "foo = 'bar'^ More? More? for idx in range(10):^ More? More? print idx" 
+3
source

Use a new line to separate statements. This is how I entered the shell:

 $ python -c "foo = 'bar' for idx in range(10): print idx" 

What you wrote does not work because the semicolon is stronger than the colon, so it gets confused. On the contrary, this works, for example:

 $ python -c "foo = 'bar'; print foo" 
+2
source

Source: https://habr.com/ru/post/1333685/


All Articles