how to use python -c on windows?

Try backtick instead of backslash.

Error:

PS C:\Users\me> python -c "def hello():\n    print('hello world')"
  File "<string>", line 1
    def hello():\n    print('hello world')
                                         ^
SyntaxError: unexpected character after line continuation character
PS C:\Users\me>

Ok:

PS C:\Users\me> python -c "def hello():`n    print('hello world')"
PS C:\Users\me>

Useful:

PS C:\Users\me> python -c "def hello():`n    print('hello world')`nhello()"
hello world
PS C:\Users\me>

Just echoing to see it:

PS C:\Users\me> echo "def hello():`n    print('hello world')`nhello()"
def hello():
    print('hello world')
hello()
PS C:\Users\me>

See PowerTip: New Lines with PowerShell


Your problem is that you are perhaps expecting \n to be translated to a newline by something ... be that the shell (cmd.exe presumably), or python itself.

Neither is doing so. Instead, if your shell is cmd.exe then you should use a line continuation character and enter an actual newline.

For example, suppose you wished to effectively echo the words blob and blub with a new line. Then you would use:

c:\>echo blob^
More? <press enter>
More? blub
blob
blub

So ... equivalently

c:\>python -c "def hello():"^
More?
More? "  print('hello world')"^
<no output, all you did was define a function>

To call it then

c:\>python -c "def hello():"^
More? <press return>
More? "  print('hello world')"^
More? <press return>
More> hello()
hello world

Tags:

Python