简体   繁体   中英

Using 'python -c' option in Windows command prompt

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?

On Windows, reverse the quoting to quote the -c argument with double quotes, eg 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, ie it prints True .

One problem is dealing with the % character on the command line, eg 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, ie ^%. 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%' .

Updating for Python 3


Windows . Only double-quoting works:

C:\> python -c "print('Hello')"
Hello

Linux . Single-quoting works as well:

$ python3 -c "print('Hello')"
Hello
$ python3 -c 'print("Hello")'
Hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM