Search code examples
python

Read python output from another python script


I have two python files, one contains code which generates an output and the other needs to read it. The generation code is:

b=5
return b

The reading code is:

import os
c= os.system("test.py")
print (c)

When I run this, the output is 1. I don't understand why this isn't 5, any advise on how to fix this please?


Solution

  • Put all the code in your first file into a function.

    #Fred.py
    def frob():
        b=5
        return b
    

    Then, you can import that function from any other Python file and see its return value.

    #Barney.py
    from Fred import frob
    print frob()
    #result: 5