1

I am trying to invoke python from within an arch linux PKGBUILD script:

python -c "from module import func; func()"

The func raises an exception, which is expected behavior but causes the script to fail. Catching the exception like this does not work:

python -c "from module import func; try: func(); except ValueError: pass"

It seems there is no way to put try/except statements into a single line (Python: try statement in a single line).

Is there another way to ignore the exception or the fact that python returns with an error? A solution that does not require additional scripts or other files would be most welcome :)

Community
  • 1
  • 1
MB-F
  • 22,770
  • 4
  • 61
  • 116

2 Answers2

3

Strings in shell can contain embedded newlines:

python -c 'from module import func
try:
  func()
except ValueError:
  pass
'

Note that this presents a challenge if the Python to run contains a mix of quotation marks, which would require some contortions to ensure they are all escaped properly. In that case, a here document would be more appropriate then the -c option (although this presents its own issues if the code to run needs to read from standard input.)

python << EOF
from module import func
try:
  func()
except ValueError:
  pass
EOF
Stefan Paul Noack
  • 3,654
  • 1
  • 27
  • 38
chepner
  • 497,756
  • 71
  • 530
  • 681
0

You can also enter the script to be executed interactively like this:

$ cat -- | python
<code here>
<code here>
<code here>
<press Ctrl-D>

and Python will run what you entered, for example:

~$ cat -- | python
from module import func
try:
  func()
except ValueError:
  pass
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module
Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111