python - 将 optparse 输入插入函数调用

标签 python python-2.7 optparse

我知道必须有更好的方法来做到这一点。所以我称之为 “我的应用程序-v 182”。我希望将 182 转换为十六进制,然后输入到我导入的另一个函数 (doThis) 中。我发现的唯一方法是使用 exec 函数有点蹩脚。我相信一定有更好的。 Python 2.7

from optparsese import OptionParser
import doThis
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage)

parser.add_option("-v", "--value", action="store", type="int", dest="value",
                  help="enter the decimal value of the hex you wish")

(options,args) = parser.parse_args()
def myFunc():
    myHex = hex(options.value)
    # the first two values are fixed, the last is what needs to supply
    doThis.withThis(0xbc,0xa3,myHex)
    # the only way I've gotten this to work is kind of lame
    exec('doThis.withThis(0xbc,0xa3,' + myHex + ')')

myFunc()

当我尝试直接插入 myHex 时,我得到典型的“没有方法匹配给定的参数”。它适用于 exec 函数,但我猜这不是正确的方法。 想法?

最佳答案

您不需要对值调用 hex():

doThis.withThis(0xbc, 0xa3, options.value)

hex() 返回一个字符串,而在 Python 代码中使用十六进制表示法则生成一个常规整数:

>>> 0xa3
163
>>> hex(163)
'0xa3'
>>> type(0xa3)
<type 'int'>
>>> type(hex(163))
<type 'str'>
>>> eval(hex(163))
163

请注意 0xa3 实际上只是用十进制拼写 163 的一种不同方式,并且 eval() 再次将值转换为整数.

optparse 无法对您在命令行中输入的“整数”值执行相同的操作;通过设置 type="int" 可以指示它识别相同的语法。来自Standard option types documentation :

if the number starts with 0x, it is parsed as a hexadecimal number

输出是一样的;命令行上的 0xa3 为您提供整数值 163:

>>> import optparse
>>> optparse._parse_int('0xa3')
163

关于python - 将 optparse 输入插入函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436078/

相关文章:

python - 如何将大型 python 项目转换为 exe 文件?

python - 如何使用for循环查找列表列表的总和

python : Converting time string with different timezone to host timezone datetime object?

python - aws - "Unable to import module ' 进程' :/var/task/numpy/core/multiarray. 所以:ELF header 无效”

ruby - OptionParser 的 make_switch 错误为 '-?'

ruby - OptParse 中带有 2 个参数的选项

python - 如何使用 Tableau 或 Excel 将数据时间转换为秒数

python - 处理 .csv 中不需要的(独立)双引号

python - 在Python中,如果初始化对象时不知道数据成员,如何使子类可见?

python - 名称 'OptionGroup' 未定义