gpt4 book ai didi

Python 尝试...除了命令行

转载 作者:行者123 更新时间:2023-12-01 06:35:50 27 4
gpt4 key购买 nike

如何使用try...except在从 bash 调用的 Python 单行代码中?

python3 -c "try: import foo\nexcept ModuleNotFoundError: print('no foo')"
  File "<string>", line 1
try: import foo\nexcept ModuleNotFoundError: print('no foo')
^
SyntaxError: unexpected character after line continuation character

最佳答案

你可以这样做:

$ python -c "
> try:
> import foo
> except ModuleNotFoundError:
> print('no foo')
> "
Traceback (most recent call last):
File "<string>", line 4, in <module>
NameError: name 'ModuleNotFoundError' is not defined

也许您应该使用 ImportError 来代替。

关于Python 尝试...除了命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59674946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com