Skip to main content
 首页 » 编程设计

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

2025年05月04日13bluestorm

我知道必须有更好的方法来做到这一点。所以我称之为 “我的应用程序-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