如何访问函数中声明的变量?

时间:2017-07-24 03:57:59

标签: python function variables python-3.6

我有以下代码:

SCRIPT1

def encoder(input_file):
    # a bunch of other code
    # some more code

    # path to output of above code
    conv_output_file = os.path.join(input_file_gs, output_format)
    subprocess.run(a terminal file conversion runs here)

if __name__ == "__main__":
    encoder("path/to/file")

这就是我尝试导入以及如何在script2中设置它的方法。

SCRIPT2

from script1 import encoder
# some more code and imports
# more code 
# Here is where I use the output_location variable to set the input_file variable in script 2
input_file = encoder.conv_output_file

我要做的是在另一个python3文件中使用变量output_location。因此,我可以告诉script2在哪里查找它正在尝试处理的文件而不对其进行硬编码。

每次运行脚本时我都会收到以下错误:

NameError: name 'conv_output_file' is not defined

3 个答案:

答案 0 :(得分:-1)

我从你的描述中得到的是你想从另一个python文件中获取一个局部变量。

返回它或使其成为全局变量,并导入它。

也许您在正确导入时遇到了一些困难。

明确这两点:

  1. 您只能以两种方式导入包:PYTHONPATH中的包或本地包。特别是,如果要进行任何相对导入,请在包名前添加.以指定要导入的包。
  2. 只有当目录下有__init__.py时,Python解释器才会将目录视为包。

答案 1 :(得分:-1)

你真的想用变量conv_output_file做什么?如果你只想获得conv_output_file绑定的值/对象,那么最好使用return语句。或者如果你想访问变量并对该变量做更多的事情,即修改它,那么你可以使用global来访问变量conv_output_file。

def encoder(input_file):
    # a bunch of other code
    # some more code

    # path to output of above code
    global conv_output_file
    conv_output_file = os.path.join(input_file_gs, output_format)

您只能在调用该函数firstscript.encoder(...)后才能从第二个脚本访问变量firstscript.conv_output_file,因为直到该函数未被调用变量才会出现。但是不建议使用全局,你应该避免使用全局。

我认为您希望获取该值而不是访问变量,因此最好使用return语句 def编码器(input_file):         #一堆其他代码         #更多代码

    # path to output of above code
    return conv_output_file
    conv_output_file = os.path.join(input_file_gs, output_format)
    return conv_output_file

或只是

     return os.path.join(input_file_gs, output_format)

答案 2 :(得分:-2)

我认为除了不返回变量或不将其声明为类变量之外,你可能会犯另一个错误。

  

告诉第二个脚本

您必须在第二个脚本中正确import第一个脚本,并使用encoder函数作为第一个脚本的属性。

例如,为您的第一个脚本encoder_script命名。 在第二个脚本中,

import encoder_script
encoder_script.encode(filename)
相关问题