将optparse输入插入函数

2024-06-08 21:41:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道必须有更好的方法来做这件事。所以我叫它 “myApp-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函数一起工作,但我猜这不是正确的方法。 思想?在


Tags: ofthe方法函数importparservalueargs
1条回答
网友
1楼 · 发布于 2024-06-08 21:41:41

不需要对值调用hex()

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

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

^{pr2}$

注意0xa3实际上只是十进制中163的另一种拼写方式,eval()又把值变成了整数。在

optparse无法对在命令行中输入的“integer”值执行相同的操作;通过设置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

相关问题 更多 >