3

I have a following script which checks whether a python module is installed or not.

{

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

} || echo "package not found!"

This is a typlical try..catch syntax of bash. If the command before && would work it will execute the command after that otherwise execute the command after ||.

But in this case, whether package is installed or not, or should I say whether the command

ipython -c 'from package import module'

returns None or ImportError, bash reads it as successful execution and prints "Successful import"

How can I check for a successful import of a python package using bash?

EDIT : And return with exit status 1?

Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74

3 Answers3

2

You can use the exception SystemExit(msg=None) with any message that's not None or 0. If it's uncaught, it'll cause the program to end, and if the msg is not None or 0, with an exit code of 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!
NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
1

Use the python command for running code snippets programmatically, instead of ipython.

There's an outstanding bug about this: https://github.com/ipython/ipython/issues/6912

gbrener
  • 5,365
  • 2
  • 18
  • 20
1

You have at least two possibilities:

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

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

  • Using 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 alot of alternatives to check for the existence of the package/module, so, intead of trying to import the package, you can check it's existence in a pythonic way. You can grab the different solutions for this answer or this and replace the import your_package; with one of them.

Community
  • 1
  • 1
Yahya Yahyaoui
  • 2,833
  • 23
  • 30