How to use variables across modules

Chris Angelico rosuav at gmail.com
Sat Nov 2 18:08:19 EDT 2013


On Sun, Nov 3, 2013 at 8:33 AM,  <juel4700 at gmail.com> wrote:
> I have a main program module called main.py and in that main.py i have this:
>
>     # Sets GPIO's to HIGH = Relays OFF
>     try:
>         import RPi.GPIO as GPIO
>     except RuntimeError:
>         Print("Error importing RPi.GPIO!!")
>
>     GPIO.setmode(GPIO.BOARD)
>     GPIO.setwarnings(False)
>     # GPIO16 is relay1
>     GPIO.setup(16, GPIO.OUT, initial=GPIO.HIGH)
>     # GPIO11 is relay2
>     GPIO.setup(11, GPIO.OUT, initial=GPIO.HIGH)
>
>
> But the function in module1 needs the GPIO from the main.py to Work. How do I go about with this? I really dont want the GPIO setting part in the module1, I dont want it to be run everytime I run the module1.Relay(1,1) call..

I don't know what GPIO is, but I suspect that you'll do best to simply
import it in module1 same as you do in main. You'll get the same
module (Python caches imported modules), so any configuration done
will apply to both.

But you might not need to separate out your modules. It's quite
alright to have a fairly large main module in Python, with lots of
functions. You'd have to figure that out separately, as a design
question.

A few other points about your code, if I may!

1) Is Print a custom function of yours? If not, please be more careful
with copying and pasting code - it makes a lot of difference.

2) If RPi.GPIO can't be imported, you emit a message and (presumably)
keep going. That's pretty useless - your script will bomb with a
NameError as soon as it tries to use GPIO. Better to simply not catch
anything around that import, and if there's a problem, the exception
will be displayed (usefully!) and the script terminated. "Have you not
heard the expression 'Never test for an error condition you don't know
how to handle'?" [1]

3) You're using Google Groups, which means your post is misformatted -
and which means that replies will be, unless you specifically work to
prevent it, very much misformatted and ugly. Please don't do that. If
you must use Google Groups, please read
https://wiki.python.org/moin/GoogleGroupsPython and follow it; but due
to the many problems with GG, there are a number of people who simply
killfile every post from there, so they won't even see it. Switching,
either to a better newsreader or to email, will solve all those
problems at once.

[1] http://www.theregister.co.uk/2008/10/24/bofh_2008_episode_34/

ChrisA



More information about the Python-list mailing list