vendredi 27 juillet 2018

How to pass input argument from one python file to another

To simplify the problem, lets say I have 4 files. And right now I arrange them like the following

main.py (where I start the program)

global important_arg
important_arg = sys.argv[1]
if __name__ == "__main__":
    import worker_a
    import worker_b
    if important_arg == "0":
        worker = worker_a.worker()
        worker.run()
    elif important_arg == "1":
        worker = worker_b.worker()
        worker.run()

worker_a/worker_b.py

import main
import helper

class worker:
    def run(self):
        a = helper.dosth()
        b = helper.dosth_2()
        ....blah blah blah

helper.py (where worker_a and b both needed static function)

import main

important_arg = main.important_arg #This is not work I know, the problem is how to make this work.

def dosth():
   ...
   #I have tiny part need important_arg
   if important_arg == "0":
        print "This is worker A."
   elif important_arg == "1":
        print "This is worker A."
   ...

def dosth_2():
   ...

For sure in this pattern, my helper.py can no longer retrieve the important_arg from the main.py.

If I force it to run, no surprise,

The error will be

'module' object has no attribute 'important_arg'

How should I redesign the pattern, or anyway to pass that arg from the main.py to helper.py?

Aucun commentaire:

Enregistrer un commentaire