将 Python 代码复制并粘贴到命令行中

将 Python 代码复制并粘贴到命令行中

当我在 Mac 终端的 Python3.9 会话中一次粘贴几行时,它不知道它们是不同的行,并且失败:

Python 3.9.1 (default, Jan  8 2021, 17:17:17) 
[Clang 12.0.0 (clang-1200.0.32.28)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 7
b = 3
a + b
  File "<stdin>", line 1
    a = 7
b = 3
a + b

         ^
SyntaxError: multiple statements found while compiling a single statement

但有趣的是,如果我在 Python2.7 中执行它,效果会很顺利:

Python 2.7.16 (default, Jun  5 2020, 22:59:21) 
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 7
>>> b = 3
>>> a + b
10

我认为我的环境或 bash_profile 中有一些东西,但为什么它只在 3.9 版本中失败?

提前致谢。米格尔.

答案1

我知道这听起来可能完全无关,但我最近遇到了类似的问题。问题是,我使用的是 Linux,无法在 Mac 上进行检查。 Bash 默认值在 5.1 中发生了变化,这是根本原因。就我而言,当我将文本粘贴到常规 shell 中时,文本也会被粘贴为“突出显示”,结果证明该设置enable-bracketed-paste off有所帮助 - 不仅对突出显示的内容有帮助,而且对 python3 shell 粘贴也有帮助,该粘贴也被破坏了一段时间。

因此,我建议您查看 Linux 发行版上的一些输入默认值/设置,这些默认值/设置可以在 .inputrc 文件中进行配置。

相关内容