For a python -c
oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:
Suppose you would like to do something like this (very similar to your sample, including except: pass
instruction):
python -c "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path
This will not work and produce this error:
File "<string>", line 1
from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
^
SyntaxError: unexpected character after line continuation character `
This is because the competition between Bash and Python interpretation of \n
escape sequences. To solve the problem one can use the $'string'
Bash syntax to force \n
Bash interpretation before the Python one.
To make the example more challenging, I added a typical Python end=..\n..
specification in the Python print call: at the end you will be able to get both \n
interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:
python -c $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path
That leads to the proper clean output without an error:
/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello
Note: this should work as well with exec
-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).
Note 2: one could work around the problem by replacing some \n
by some ;
but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.
Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of \n
escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.