Python 如何从整个函数返回单个变量?
我希望在python中从整个函数返回一个变量,并在另一个python脚本中仅使用该变量。我该怎么做呢。我尝试了以下方法: 脚本A:Python 如何从整个函数返回单个变量?,python,python-2.x,Python,Python 2.x,我希望在python中从整个函数返回一个变量,并在另一个python脚本中仅使用该变量。我该怎么做呢。我尝试了以下方法: 脚本A: 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'}
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
所以脚本A给了我一个定义为val
的值,我只想导入
这个值,但是当我将脚本A导入脚本B时,它会运行整个函数,包括打印测试。内容
。我该怎么做呢
脚本B:
from scripta import adding
调用函数并存储结果:
#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
这就是为什么您首先要使用return语句。因此,您可以在其他地方传递局部变量的值,调用函数就是实现这一点的方法。调用函数并存储结果:
#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
这就是为什么您首先要使用return语句。因此,您可以在其他地方传递局部变量的值,调用函数是实现这一点的方法。您不能执行部分函数,它将执行整个函数。如果不希望打印行成为函数的一部分,则必须将其删除 此外,如果在
scripta
中的函数之外有代码,则必须使用if\uuuu name\uuuu
子句对其进行保护,以防止在导入时执行它
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:
from scripta import adding
result = adding() # the result variable will have what you returned (val)
不能执行部分函数,它将执行整个函数。如果不希望打印行成为函数的一部分,则必须将其删除 此外,如果在
scripta
中的函数之外有代码,则必须使用if\uuuu name\uuuu
子句对其进行保护,以防止在导入时执行它
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:
from scripta import adding
result = adding() # the result variable will have what you returned (val)
如果你想访问脚本B中的
val
,你必须作为某个点运行函数?如果你想访问脚本B中的val
,你必须作为某个点运行函数?