1

How can I use try...except in a Python one-liner invoked from bash?

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
z0r
  • 8,185
  • 4
  • 64
  • 83

1 Answers1

1

You may do it like this:

$ 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

Probably you should have used ImportError instead.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
lenik
  • 23,228
  • 4
  • 34
  • 43
  • Thanks! Turns out my question was a duplicate. Your solution works, but I ended up using `$'...\n...'` to interpret the newlines. Also, I'm using Python 3 which is why it raises `ModuleNotFoundError`. Sorry, I wasn't clear in my question. – z0r Jan 10 '20 at 03:26
  • @z0r I rolled back your edit since it fundamentally changed the code. The main problem is that `ModuleNotFoundError` is defined in Python 3, so it won't raise a `NameError`. I would normally say post your own answer instead, but the question's already been closed as a duplicate... – wjandrea Jan 10 '20 at 03:39
  • @wjandrea thank you very much! – lenik Jan 10 '20 at 05:11