Python 将optpass输入插入函数调用
我知道一定有更好的办法。所以我称之为 “myApp-v 182”。我想把182转换成十六进制,然后输入我导入的另一个函数(doThis)。我发现的唯一方法是使用exec函数。我相信一定有更好的办法。Python 2.7Python 将optpass输入插入函数调用,python,python-2.7,optparse,Python,Python 2.7,Optparse,我知道一定有更好的办法。所以我称之为 “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
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
>>> import optparse
>>> optparse._parse_int('0xa3')
163