我知道必须有更好的方法来做这件事。所以我叫它 “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函数一起工作,但我猜这不是正确的方法。 思想?在
不需要对值调用
hex()
:
^{pr2}$hex()
返回一个字符串,而在Python代码中使用十六进制表示法将生成一个常规整数:注意
0xa3
实际上只是十进制中163
的另一种拼写方式,eval()
又把值变成了整数。在optparse
无法对在命令行中输入的“integer”值执行相同的操作;通过设置type="int"
可以指示它识别相同的语法。从Standard option types documentation:并且输出是相同的;
0xa3
在命令行上给您一个整数值163
:相关问题 更多 >
编程相关推荐