我正在尝试为某些python构建脚本执行一些脚本重用。我的“可重用”部分的缩写版本看起来像(_build.py):
Sources = []
Sources += glob('*.c')
Sources += glob('../FreeRTOS/*.c')
...
def addSources(directory, *rest):
for each in rest:
Sources += ['../'+directory+'/'+each+'.c']
def addSharedSources(*args):
addSources('Shared', *args)
然后在自定义部分,我有类似(build.py):
#!/usr/bin/env python
from _build import *
...
#Additional source files from ../Shared, FreeRTOS and *.c are already in
addSharedSources('ccpwrite', 'discovery', 'radioToo', 'telemetry', 'utility')
不幸的是,当我尝试运行build.py时,我得到的回溯看起来像:
Traceback (most recent call last):
File "./build.py", line 8, in <module>
addSharedSources('ccpwrite', 'discovery', 'radioToo', 'telemetry', 'utility')
File "/Users/travisg/Projects/treetoo/Twig/_build.py", line 49, in addSharedSources
addSources('Shared', *args)
File "/Users/travisg/Projects/treetoo/Twig/_build.py", line 46, in addSources
Sources += ['../'+directory+'/'+each+'.c']
UnboundLocalError: local variable 'Sources' referenced before assignment
所以即使我进行了通配符导入,看起来当调用导入函数时,它不会引用从原始导入的“全局”变量。有没有办法让它发挥作用?我玩弄了global
,但这似乎没有我想要的。
答案 0 :(得分:2)
这与导入无关。如果直接运行_build.py
,则会遇到同样的问题。问题是函数addSources
正在修改全局Sources
而不将其声明为全局。在global
函数中插入addSources
声明,一切都应该正常。
说明:错误地编写这种代码非常容易。所以python允许你读取一个全局变量,而不是将其声明为全局变量,而不是修改它。