How to catch python ImportError as wrapper

I have the following script that checks if the python module is installed or not.

{

ipython -c 'from package import module' && echo "Successful import"

} || echo "package not found!"

      

This is typical try..catch

bash syntax . If the command before && works, it will execute the command after that, otherwise it will execute the command after ||.

But in this case, is it installed package

or not, or should I say if the command is

ipython -c 'from package import module'

      

returns None

or ImportError

, bash reads it as success and prints "Import succeeded"

How can I check if a python package has been imported successfully using bash?

EDIT: And return with exit status 1?

+3


source to share


3 answers


You have at least two options:

  • Using "pip" on your shell script to get a list of installed packages, then grep for package tour:

    peak list | grep yourpackage && & installed echo || echo "NOT Installed"

  • Using a Python-bash script, I don't know exactly how to call it, but I know how to use it:

Something like:



output=$(
python - <<EOF
try:
    import your_package;
    print "Package Installed"
except Exception:
    print "Package not installed"
EOF
)

echo $output

      

here you have many alternatives to check if a package / module exists, so to try and import a package you can check its existence on a pythonic path. You can find various solutions for this or and replace import your_package;

with one of them.

+1


source


You can use an exception SystemExit(msg=None)

with any message that is not None

or 0

. If this fails, it will cause the program to terminate, and if msg

not None

or 0

, with an exit code 1

. (see https://docs.python.org/3/library/exceptions.html#SystemExit ).

test.py

try:
    import Blue
except ImportError:
    raise SystemExit("Import Error!")

      



in bash:

[user]@[host] $ python test.py 
Import Error!

[user]@[host] $ python test.py || echo "blarg"
Import Error!
blarg

[user]@[host] $ python test.py && echo "blarg"
Import Error!

      

+2


source


Use the command python

for snippets programmatically, not ipython

.

There is a prominent bug there: https://github.com/ipython/ipython/issues/6912

+1


source







All Articles