我有一个简单的脚本,它使用I2C将命令(十六进制值)传递给uC。我想通过命令行传递地址和命令值as argv' s。
这是我的代码:
import smbus
import time
from sys import argv
bus = smbus.SMBus(1)
addr = argv[1]
cmd = argv[2]
#address is 0x09
#commands = [0x16,0x06,0x17,0x07,0x18,0x08,0x19,0x09]
bus.write_byte(addr,cmd)
我试过写
python progam.py 0x09 0x19
python program.py 9 25
并且还尝试将argv转换为int()然后转换为hex。这些都没有奏效。
如何将十六进制值传递到我的程序中?
答案 0 :(得分:2)
import smbus
import time
from sys import argv
bus = smbus.SMBus(1)
if sys.argv[1].startswith("0x"): # base 16
addr = int(argv[1][2:],16)
cmd = int(argv[2][2:],16)
else: # base 10
addr = int(argv[1])
cmd = int(argv[2])
print [addr,cmd] # you should see no quotes indicating that these are indeed ints now
bus.write_byte(addr,cmd)
然后用$ python my_script.py 9 25
调用它
或者使用$ python my_script.py 0x09 0x19