python - 有条件地调用另一个脚本中的函数并使用它的变量
问题描述
我有两个脚本,一个在 Python 27 中调用另一个。第一个脚本 Script1.py 包含一些条件语句。然后我有第二个脚本 Script2.py,它调用第一个脚本并将参数传递给从第一个脚本导入的函数 func1。
但是,当我运行第二个脚本时,我得到一个错误,即未定义 func1 中的变量。为什么是这样?我该怎么做才能解决?
谢谢
脚本1.py:
def func1(var):
if var == '1':
test1 = 'a'
test2 = 'b'
test3 = 'c'
if var == '2':
test1 = 'd'
test2 = 'e'
test3 = 'f'
脚本2.py:
from Script1 import func1
func1('1')
print test1, test2, test3
func1('2')
print test1, test2, test3
Traceback (most recent call last):
File "G:/Python27/Script2.py", line 5, in <module>
print test1, test2, test3
NameError: name 'test1' is not defined
解决方案
def func1(var):
if var == '1':
test1 = 'a'
test2 = 'b'
test3 = 'c'
elif var == '2':
test1 = 'd'
test2 = 'e'
test3 = 'f'
# to catch error when different argument is passed
else:
test1 = test2 = test3 = None
return test1, test2, test3 # return the variables, so they can be used outside
和:
from Script1 import func1
test1, test2, test3 = func1('1')
print test1, test2, test3
test1, test2, test3 = func1('2')
print test1, test2, test3
推荐阅读
- java - Java 通过 ctrl click 检测在 OSX 上释放了哪个 mouseButton
- algorithm - 为什么“1”的 CRC 会产生生成多项式本身?
- jquery - 处理响应式网页中的事件
- grails - 如何在约束自定义验证中访问 url 映射参数?
- javascript - 使用 Angular 6 我们如何捕获特定的 div 或页面组件?
- android - 解码错误,Azure 不支持图像格式
- reactjs - React-Native-Sqlite,我应该让 db.open db.close 每个查询吗?
- javascript - FindOne() 工作返回记录,但不能为 Node.js 使用 MongoDB 聚合查询(ids 的总和记录)
- android - Theme.MaterialComponents 不会改变对话框标题的字体
- sql - 如何更改输出类型?