[英]Using 'python -c' option in Windows command prompt
I want to execute a python script string directly from command prompt in Windows .我想直接从 Windows 中的命令提示符执行python脚本字符串。
So after a bit of googling, I found the python -c
option.因此,经过一番谷歌搜索后,我找到了python -c
选项。
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相同的命令在 Ubuntu 中运行良好,它打印
hello
How can I execute a python command directly in windows command prompt?如何在 windows 命令提示符中直接执行 python 命令?
On Windows, reverse the quoting to quote the -c
argument with double quotes, eg python -c "print 'Hello'"
.在 Windows 上,反向引用以使用双引号引用-c
参数,例如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 .命令行由 python.exe 中的 C 运行时启动代码解析,该代码遵循解析 C++ 命令行参数中列出的规则。 Additionally cmd.exe generally ignores many special characters (except %) in double-quoted strings.此外,cmd.exe 通常会忽略双引号字符串中的许多特殊字符(% 除外)。 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'
.例如, python -c 'print 2 > 1'
不仅 Python 无法正确解析,而且 cmd.exe 会将stdout
重定向到名为1'
的文件。 In contrast, python -c "print 2 > 1"
works correctly, ie it prints True
.相比之下, python -c "print 2 > 1"
工作正常,即它打印True
。
One problem is dealing with the % character on the command line, eg python -c "print '%username%'"
.一个问题是处理命令行上的 % 字符,例如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 %^.如果不希望 cmd.exe 扩展环境变量,可以使用 %^ 将引号外的 % 转义。 The ^ character is cmd's escape character, so you'd expect it to be the other way around, ie ^%. ^ 字符是 cmd 的转义字符,因此您希望它是相反的,即 ^%。 However, cmd actually doesn't use ^ to escape %.但是,cmd 实际上并不使用 ^ 来转义 %。 Instead it prevents it from being parsed with username%
as an environment variable.相反,它会阻止它被解析为username%
作为环境变量。 This requires quoting the -c
argument in sections as follows: python -c "print '"%^"username%'"
.这需要在以下部分中引用-c
参数: 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%'
.在这种特殊情况下,由于命令的其余部分没有空格或特殊字符,因此可以更简单地写为python -c "print "'%^username%'
。
Windows .窗户。 Only double-quoting works:只有双引号有效:
C:\> python -c "print('Hello')"
Hello
Linux . Linux . Single-quoting works as well:单引号也可以:
$ python3 -c "print('Hello')"
Hello
$ python3 -c 'print("Hello")'
Hello
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.