在Windows命令提示符中使用'python -c'选项 [英] Using 'python -c' option in Windows command prompt

查看:115
本文介绍了在Windows命令提示符中使用'python -c'选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想直接在 Windows 的命令提示符下执行python脚本 string

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

因此有点谷歌搜索,我发现 python -c 选项。

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

我做到了,

python -c 'print "Hello"'

但是出现以下错误,

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

时,EOL在Ubuntu上运行良好,可以打印

The same command is working fine in Ubuntu, it prints

hello

如何直接在Windows命令提示符下执行python命令?

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

推荐答案

在Windows上,请反引号将 -c 参数用双引号引起来,例如 python -c print'Hello'

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

命令行由C中的C运行时启动代码解析python.exe,它遵循解析C ++命令行参数中列出的规则。此外,cmd.exe通常会忽略双引号字符串中的许多特殊字符(%除外)。例如, python -c’print 2> 1'不仅没有被Python正确解析,而且cmd.exe将 stdout 重定向到名为 1'的文件。相反, python -c print 2> 1 可以正常工作,即它打印 True

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.

一个问题是在命令行中处理%字符,例如 python -c打印'%username%' 。如果您不希望使用cmd.exe扩展环境变量,则可以使用%^将引号之外的%换码。 ^字符是cmd的转义字符,因此您希望它反过来,即^%。但是,cmd实际上并不使用^来转义%。相反,它防止使用 username%作为环境变量来解析它。这需要在各节中引用 -c 参数,如下所示: python -c print'%^ username%' 。在这种情况下,由于命令的其余部分没有空格或特殊字符,因此可以更简单地写为 python -c print'%^ username%'

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

这篇关于在Windows命令提示符中使用'python -c'选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆