Using 'python -c' option in Windows command prompt

前端 未结 1 1807
广开言路
广开言路 2021-01-07 06:15

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

So after a bit of googling, I found the pyt

相关标签:
1条回答
  • 2021-01-07 06:31

    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%'.

    0 讨论(0)
提交回复
热议问题