简体   繁体   English

如何从整个函数返回单个变量?

[英]How to return a single variable from a whole function?

I would like to return a single variable from a whole function in python and use only that one variable in another python script. 我想从python中的整个函数返回一个变量,而在另一个python脚本中仅使用一个变量。 How would I go about in doing this. 我将如何去做。 I have tried the following: 我尝试了以下方法:

scripta: 脚本:

def adding(self):
   s = requests.Session()
   test = s.get('url')
   print test.content 
   soup = BeautifulSoup(test.content,'html.parser')
   val = soup.find('input', {'name': 'id'})
   return val

So Script A gives me a value defined as val , I want to import only this value, however when I import script A into script B it runs the whole function including the print test.content . 因此,脚本A给我提供了一个定义为val的值,我只想import该值,但是当我将脚本A导入到脚本B中时,它将运行包括print test.content在内的整个函数。 How would I go about doing this? 我将如何去做呢?

Script B: 脚本B:

from scripta import adding

You can't execute a partial function, it will execut the whole function. 您无法执行部分功能,它将执行整个功能。 You have to remove the print line if you don't want it to be a part of the function. 如果您不希望它成为功能的一部分,则必须删除它。

Also, if you have code outside the function in scripta , you have to protect it with a if __name__ clause to prevent it to be executed on import. 另外,如果您在scripta 的函数之外有代码,则必须使用if __name__子句对其进行保护,以防止在导入时执行它。

scripta.py: scripta.py:

import requests
from BeautifulSoup import BeautifulSoup

def adding():
   s = requests.Session()
   test = s.get('url')
   # print test.content 
   soup = BeautifulSoup(test.content,'html.parser')
   val = soup.find('input', {'name': 'id'})
   return val

if __name__ == '__main__':
     # this part will only run if this is the main script. 
     # when starting scriptb first and importing this part won't run
     print adding()

scriptb.py: scriptb.py:

from scripta import adding
result = adding() # the result variable will have what you returned (val)

Call the function and store the result: 调用该函数并存储结果:

#Script A:
def adding():
    # remove "self" param, it is not used (and this does not 
    # seem to be a method of a class)
    # ...

#Script B:
from scripta import adding

xyz = adding()  # variable name does not matter
# do stuff with xyz

That's why you have the return statement in the first place. 这就是为什么首先要有return语句的原因。 So you can communicate the value of the local variable elsewhere, and calling the function is the way to do that. 因此,您可以在其他地方传递局部变量的值,调用函数是实现此目的的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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