user1692342
user1692342

Reputation: 5237

Execute a Python script inside Python and pass arguments to it and get the value returned

I want to execute a piece of Python code [B] from my existing Python code [A]. In B I would like to access methods defined in A. From A I would like to pass arguments to B.

If I try this way:

B.py

def Main(args):
   print(args)
   method_a()  # this doesn't work

A.py

def method_a():
   return 5
mod = importlib.import_module('B')
mod.Main(123)

Using import_module I do not have access to methods in A.py

If I use eval then I cannot pass any arguments to it and I'm not able to execute an entire file: eval('print(123)') works but eval(open('B.py').read()) does not.

If I use exec I can access methods from A.py but I cannot return any value or pass any arguments. I'm Using python 3.6

Upvotes: 0

Views: 254

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

Wrong design - two modules (or a module and a script - the only difference is how it's used) should not depend on each other. The correct way to structure your code is to have your "library" code (method_a etc) in one (or more) modules / packages that are totally independant of your application's entry point (your "main" script), and a main script that depends on your library code.

IOW, you'd want something like this:

# lib.py

def method_a(args):
    print(args)
    return 42

def method_b():
    # do something

# etc

And

# main.py

import sys
import lib

def main(args):
    print(lib.method_a(args))

if __name__ == "__main__":
    main(sys.argv)

Upvotes: 3

Related Questions