2015-02-24 121 views
0

我正在創建安裝文件,首先檢查是否已安裝特定軟件包,如果是,則打印它的版本,否則安裝該軟件包。驗證安裝,打印版本,如果已安裝,否則安裝該包

考慮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

有更好的方法嗎?

+2

可以趕上'ImportError'。 – 2015-02-24 13:06:19

回答

1

你可以這樣做

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"