Search code examples
pythonsmbus

Python pass input string which has spaces and use for smbus


My code for ic2 is.

import argparse
import smbus
import time

bus = smbus.SMBus(1)

bus.write_byte_data(0x20, 0x00, 0x00)
bus.write_byte_data(0x20, 0x01, 0x00)
bus.write_byte_data(0x20, 0x14, 0x01)    
time.sleep(0.5) 
bus.write_byte_data(0x20, 0x12, 0x00)
time.sleep(0.5) 

It work fine.

And I test this code.

import argparse
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]
print 'Params=', var1, var2, var3

By

python test.py  0x20 0x14 0x01
Params= 0x20 0x14 0x01 

But when I try code to.

import argparse
import sys
import smbus
import time

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

bus = smbus.SMBus(1)

bus.write_byte_data(0x20, 0x00, 0x00)
bus.write_byte_data(0x20, 0x01, 0x00)
bus.write_byte_data(var1, var2, var3)    
time.sleep(0.5) 
bus.write_byte_data(0x20, 0x12, 0x00)
time.sleep(0.5) 

python test.py 0x20 0x14 0x01

Traceback (most recent call last): File "test.py", line 16, in bus.write_byte_data(var1, var2, var3)
TypeError: an integer is required

How can I fix it?


Solution

  • Your argument values look like HEX. Are you calling this via batch or bash? Python can distinguish HEX and decimal automatically, batch/bash can not.

    In this case, although you submit HEX to sys.argv[x], bash/batch thinks it's a string and submits the string to python. Therefore, you need to convert to HEX int explicitly.

    var1 = int(sys.argv[1], 16) # The '16' defines the base here
    var2 = int(sys.argv[2], 16) # Base '16' converts HEX string to HEX int
    var3 = int(sys.argv[3], 16) # You must set base to '16' here
    

    NB: If you want a non-HEX int number ('normal' integer), you can convert by using base 0 rather than 16 (see here).