Search code examples
pythonrfid

Python try finally statement to run another file


I am having an issue getting my try and finally statement to execute properly. I am trying to get another Python file to execute once a user has interacted with the first program.For example, once the first program is run the user will be asked to scan their tag which will create a unique user id for that user; after their tag is scanned a second python file will be executed. My problem is that the second file is constantly being run as soon as the first file is executed regardless if the tag is scanned first or not. I have added my code below with comments to help explain better. Any thoughts?

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

# Second File being ran
import medform

reader = SimpleMFRC522()  

try:

# user id being created
   c = string.ascii_letters + string.digits
   op = "".join(choice(c) for x in range(randint(8,16)))

# Printed before tag is scanned
   print("Please Scan tag " )
   reader.write(op + op)

# if tag is scanned / id created open second file 
   if reader.write(op + op):
      os.system('python medform.py')
   else:
      print("Scan Tag First" )

# Print after tag is scanned 
  print("Scan Complete")

 finally:
    GPIO.cleanup()

Solution

  • importing a file runs it, there are 2 ways to do what you want:

    1. import the file when you want it to run
    2. define a main function in the other file that you can run from the first one instead of having all the code in the top level

    the second option is the best one in most cases, as you normally would not want a file to actually do stuff on import.

    so in the second file you would have:

    def main():
       # the code you want to run (make sure to indent it)
    

    then in the first you can have:

    import medform
    # ...
    medform.main()