验证安装,如果已安装则打印版本,否则安装该软件包

Verify installation, print version if already installed otherwise install that package

我正在创建安装文件,首先我检查特定的包是否已经安装,如果是然后打印它的版本,否则安装那个包。

考虑nltk,我是这样做的:

nltkv = '{}.'.format(nltk.__version__)
if nltkv == '':
    print "Nltk is not installed, Let's start installing .../n"
    subprocess.call('sudo pip install -U nltk', shell = True)
    #sudo easy_install pip
else:
    print "nltk is already installed, V : /n", nltkv

但是为此我需要做 import nltk

所以,如果 nltk 尚未安装,那么它会在第一行给出错误:

  File "setup.py", line 1, in <module>
    import nltk
ImportError: No module named nltk

有几个这样的软件包需要验证和安装。我正在使用 ubuntu 和 python

是否存在更好的方法?

你可以这样做

import subprocess 
try:
    import nltk
    nltkv = '{}.'.format(nltk.__version__)
    print "nltk is already installed, V : \n", nltkv # mind the escape sequence
except ImportError:
    print "Nltk is not installed, Let's start installing ...\n"
    subprocess.call('sudo pip install -U nltk', shell = True)
    #sudo easy_install pip
except:
    print "Some error occurred!\n"