简体   繁体   中英

Change Python Versions to call two different modules

I have a simple program in which I am using two modules ie sqlite3 and twython. Now the sqlite3 is for python2.6 and twython is for 2.7. So if I change my shebang line to 2.6 then twyhton fails ie

python2.6 t_first.py
ImportError: No module named twython

And if I do following

python2.7 t_first.py
ImportError: No module named _sqlite3

Any solution. Also virtualenv is not a best solution here.

sqlite3 is usually a builtin for python (in 2.6 and 2.7). I suggest that you install a non-broken version of python 2.7, and install twython into the site-packages for that. If you don't want to do that, install twython into the 2.6 site-packages.

you could use exception handling to manage the import process. Something along the lines of:

try:
    import twython
except ImportError:
    import _sqlite3

This works if you assume that you need either one of the two present in any context. This would provide a preference to twython and fall back to _sqlite3 if twython is not available. It is an acceptable logical equivalent to:

if "twython exists" import twython else import _sqlite3 

If you want to be more specific about the environments you could also do the following:

import sys
if sys.version_info == (2, 6):
    import _sqlite3
elif sys.version_info == (2, 7):
    import twython

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM