ry_wang
V2EX  ›  Python

请各位看下这个Python版本兼容的问题.

By ry_wang at 2012 年 12 月 11 日 · 5099 次点击
一个应用程序需要通过argparse模块解析传参,但argparse是Python2.7以上有的,Python2.6的需要使用optparse这个模块.

所以在导入模块以及创建实例时的时候我使用如下方法来做.

try:
from argparse import ArgumentParser
except:
from optparse import OptionParser as ArgumentParser

parser = ArgumentParser()

但是这时候发现一个苦逼的问题.
argparse这个模块使用add_argument()来定义参数解析.如下:
parser.add_argument('address', help='server address')
parser.add_argument('-u', dest='username', help='username')
parser.add_argument('-p', dest='port', help='port')

可optparse这个模块是使用add_option()方法来定义参数....

请问各位,这种情况应该如何避归呢?分Python版本来分别做?统一使用optparse这个模块?

我现在的想法是按照下面这样来搞?相当于闹个别名?

class MyArgumentParser(ArgumentParser):

def __init__():
pass

def my_add_argument():
pass


谢谢.
12 条回复  •  1970-01-01 08:00:00 +08:00
bhuztez
   1
bhuztez  
   2012 年 12 月 11 日
pip install argparse
ry_wang
   2
ry_wang  
OP
   2012 年 12 月 11 日
@bhuztez 能装我还费这劲,55555
timonwong
   3
timonwong  
   2012 年 12 月 11 日
argparse should work on Python >= 2.3, it was tested on:

2.3.5, 2.4.4, 2.5.5, 2.6.5 and 2.7
3.1, 3.2

http://pypi.python.org/pypi/argparse

直接包含进代码的Libs中吧。
只需要 argparse.py 和其 LICENSE
ry_wang
   4
ry_wang  
OP
   2012 年 12 月 11 日   ❤️ 1
@timonwong 这是最后实在不行的办法.
还是希望能有方法解决这个问题,因为后续可能还会有这种需求.
CoX
   5
CoX  
   2012 年 12 月 11 日
为啥不直接用 optparse呢,反正2.7里有这个模块
ry_wang
   6
ry_wang  
OP
   2012 年 12 月 11 日
@CoX 哈哈,万一以后optparse这个模块在新版本的Python下没了呢.
我好纠结.哈哈.
CoX
   7
CoX  
   2012 年 12 月 11 日
@ry_wang

try:
from argparse import ArgumentParser
parser=ArgumentParser.add_argument
except:
from optparse import OptionParser as ArgumentParser
parser=ArgumentParser.add_option

parser('-p', dest='port', help='port')

不过感觉真没必要考虑那么多:)
bhuztez
   8
bhuztez  
   2012 年 12 月 11 日
@ry_wang 直接把文件复制过去啊,反正就一python文件
clowwindy
   9
clowwindy  
   2012 年 12 月 11 日
这就是我用 getopt 的原因
yupbank
   10
yupbank  
   2012 年 12 月 12 日
要不,自己把不靠谱的接口全部山寨一遍吧,以后发现不兼容的,就在前面换。
BOYPT
   11
BOYPT  
   2012 年 12 月 12 日
计算机领域的一切问题,都可以通过增加一个抽象层解决……
ry_wang
   12
ry_wang  
OP
   2012 年 12 月 12 日
主要是我这个人比较隔路,有系统默认模块的就不愿意再装其它的,可以程序层面简单避归掉的就想在程序上做.但是呢,程序还不能太丑...
就像能一个awk里做完的分析,绝对不用awk+grep来做....
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 44ms · 3.9.8.5