Using 'python -c' option in Windows comman

2020-07-31 07:19发布

问题:

I want to execute a python script string directly from command prompt in Windows.

So after a bit of googling, I found the python -c option.

I did,

python -c 'print "Hello"'

But it's giving the following error,

  File "<string>", line 1
    'print
         ^
SyntaxError: EOL while scanning string literal

The same command is working fine in Ubuntu, it prints

hello

How can I execute a python command directly in windows command prompt?

回答1:

On Windows, reverse the quoting to quote the -c argument with double quotes, e.g. python -c "print 'Hello'".

The command line is parsed by the C runtime startup code in python.exe, which follows the rules as listed in Parsing C++ Command-Line Arguments. Additionally cmd.exe generally ignores many special characters (except %) in double-quoted strings. For example, python -c 'print 2 > 1' not only isn't parsed right by Python, but cmd.exe redirects stdout to a file named 1'. In contrast, python -c "print 2 > 1" works correctly, i.e. it prints True.

One problem is dealing with the % character on the command line, e.g. python -c "print '%username%'". If you don't want the environment variable to be expanded by cmd.exe, you can escape % outside of quotes with %^. The ^ character is cmd's escape character, so you'd expect it to be the other way around, i.e. ^%. However, cmd actually doesn't use ^ to escape %. Instead it prevents it from being parsed with username% as an environment variable. This requires quoting the -c argument in sections as follows: python -c "print '"%^"username%'". In this particular case, since the rest of the command doesn't have spaces or special characters, this could be written more simply as python -c "print "'%^username%'.