首页 > 解决方案 > 如何在 Windows 上使用 python -c?

问题描述

https://docs.python.org/3/using/cmdline.html

这是选项文档。但它没有为我提供任何有用的信息

我想以这种方式执行代码

python -c "def hello():\n    print('hello world')"

错误信息

PS C:\Users\Administrator> python -c "def hello():\n    print('hello world')"
  File "<string>", line 1
    def hello():\n    print('hello world')
                                         ^
SyntaxError: unexpected character after line continuation character

它适用于Linux,但不适用于Windows。

希望大家能给个完整的固定命令~~~

使用 javascript 执行“python -c”时与这个 \n 问题相关的另一个问题

标签: python

解决方案


尝试使用反引号而不是反斜杠。

错误:

PS C:\Users\me> python -c "def hello():\n    print('hello world')"
  File "<string>", line 1
    def hello():\n    print('hello world')
                                         ^
SyntaxError: unexpected character after line continuation character
PS C:\Users\me>

好的:

PS C:\Users\me> python -c "def hello():`n    print('hello world')"
PS C:\Users\me>

有用:

PS C:\Users\me> python -c "def hello():`n    print('hello world')`nhello()"
hello world
PS C:\Users\me>

只是回声看到它:

PS C:\Users\me> echo "def hello():`n    print('hello world')`nhello()"
def hello():
    print('hello world')
hello()
PS C:\Users\me>

请参阅PowerTip:PowerShell 的新行


推荐阅读