技术小黑屋

Check if a Python Module Is Installed

I was once stucked in How to check Whether a Python module has been installed or not. After Googling, I found this trick.
Python allows user to pass command from out of a python file.See here

1
-c cmd : program passed in as string (terminates option list)

The result if we import an installed module

1
2
3
4
20:15:45-androidyue~/osc_git/LnxClient (master)$ python -c "import os"
20:31:24-androidyue~/osc_git/LnxClient (master)$ echo $?
0
#0 means the module has been installed

Now if we import an module which is not installed.

1
2
3
4
5
6
7
20:31:41-androidyue~/osc_git/LnxClient (master)$ python -c "import aaa"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named aaa
20:31:46-androidyue~/osc_git/LnxClient (master)$ echo $?
1
#1 means that module is not installed.

Others





快来解锁最新版 Typora,新用户券后仅需 84 元!
如何便宜的购买 office 365 ?
新版赤友 NTFS 助手来袭,正版超低价