I have two .py script files. The "main" script will import the second script containing misc "helper" functions.
In the main script, I have set up an object for a SPI interface. I would like to write functions in the imported file that use the SPI interface directly. I'm a noob at this and tried writing and passing in various ways but always get errors.
mainscript.py
import helperfunctions.py as helper
spi = spidev.SpiDev()
spi.open(0, 0)
response = spi.xfer([ ... some data ...]) #this works when
#called from mainscript.py
helper.sendOtherStuff() #this doesn't work (see helper script below)
helperfunctions.py
def sendOtherStuff():
#need to somehow reference 'spi.' object from mainscript.py file
otherData = ([... some different data ...])
resp = spi.xfer([otherData]) #this fails because helperfunctions
#apparently doesn't know spi. object
return resp
I have the same general question often regarding global variable values as well. I'm sure there is a "better" way to do it, but out of convenience for now, I often wish to define some global variables in mainscript.py then reference those globals inside functions of helperfunctions.py. I can't figure a way to do this. Going the other way is easy - declare the globals inside helperfunctions.py then reference them from mainscript.py as helper.variableName, but I don't know how to go the other direction.
Any direction is much appreciated. Thank you.
By my lights the easiest thing to do would be to pass the spi object to the helper function as a parameter:
def sendOtherStuff(spi):
otherData = ([... some different data ...])
return spi.xfer([otherData])
Once it's passed in, you can call methods on it in the body of the function. I removed your variable assignment because it seemed redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With