-5

I have two Python projects, A and B.

A was developed before B, and it has its own main function.

Then B was developed, and I'd like to call project A from B, that is, A is a part of B.

May I know how can I archive my goal?

Many thanks.

ChangeMyName
  • 7,018
  • 14
  • 56
  • 93
  • something like that can be achieved with python classes I guess. – Maddy Dec 18 '14 at 16:59
  • look up python's `include` statement. In project A, make execution of `main` conditional by putting it under `if __name__ == "__main__":`. That's all you need. – alexis Dec 19 '14 at 14:57

1 Answers1

2

You haven't included much information about your actual problem and how you have attempted to solve it. So I am going to have a good guess at what your issue is and see if I can help.

You probably have code that looks a little like this:

def do_one_thing():
    ...

def do_something_else():
    ...

do_one_thing()
do_something_else()

And when you try importing that into your B script, you find that the code is executed immediately. The fix for this is quite simple. When you have top level commands you need to only execute them when the script is directly invoked rather than being imported.

In the above code example the statements do_one_thing() and do_something_else() are the top level commands that I am talking about.

If you use the if __name__ == "__main__": stanza then you can execute those top level commands only when the file is directly executed. You can find out more about that here. If I make that change to the above code, it becomes:

def do_one_thing():
    ...

def do_something_else():
    ...

if __name__ == "__main__":
    do_one_thing()
    do_something_else()

And the file can now be imported, allowing access to the methods defined within.

Community
  • 1
  • 1
Matthew Franglen
  • 4,441
  • 22
  • 32