简体   繁体   中英

How to get return output from another script?

How can i get the output from another script?

My first script to run:

from test2 import *
class Test():
    def todo (self):
        mult()
        addx()

if __name__ == '__main__':
    Test().todo()

My second script named (test2.py ):

def mult():
    x= 2 * 4
    print(x)
    return x

def addx():
    sum = x + 2
    print("sum",sum)

Error:

NameError: name 'x' is not defined

In the function addx() you haven't declared x . I believe you want x from mult . So you can do something like this

def addx():
    x = mult()
    sum = x + 2
    print("sum",sum)

You should use the return value of mult , to pass it to your second function addx as a parameter.

def todo (self):
    x = mult()
    addx(x)

I advise you to read the Python doc section about function : https://docs.python.org/fr/3/tutorial/controlflow.html#defining-functions

In test2.py , you have not defined x

def addx():
sum = x + 2
print("sum",sum)

The problem above is that the computer doesn't know what x is. You could pass it as a parameter:

def addx(x):
sum = x + 2
print("sum", sum)

and change your code to:

from test2 import *

class Test():
    def todo(self):
        addx(x=mult()) # whatever number you want

if __name__ == '__main__':
    Test().todo()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM