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

2024-04-26 00:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

脚本1

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中设置它。你知道吗

脚本2

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\u location。因此,我可以告诉script2在何处查找它试图处理的文件,而不必硬编码它。你知道吗

每次运行脚本时,我都会出现以下错误:

NameError: name 'conv_output_file' is not defined

Tags: oftopathname脚本encoderinputoutput
3条回答

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

tell that 2nd script

您必须正确地将第一个脚本import转换为第二个脚本,并将encoder函数用作第一个脚本的属性。你知道吗

例如,将第一个脚本命名为encoder_script。 在第二个剧本里

import encoder_script
encoder_script.encode(filename)

我从您的描述中得到的是,您希望从另一个python文件中获取一个局部变量。你知道吗

返回它或使其成为全局变量,然后导入它。你知道吗


可能您在正确导入时遇到了一些困难。你知道吗

明确这两点:

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

您实际想要对变量conv\u output\u文件做什么?如果您只想获取conv\u output\u文件绑定到的值/对象,那么最好使用return语句。或者,如果您想访问该变量并对该变量执行更多操作(即修改它),则可以使用global访问变量conv\u output\u文件。你知道吗

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)

现在可以从第2个脚本访问变量firstscript.conv\输出\文件只有在调用该函数之后firstscript.encoder文件(…)因为在函数未被调用之前,变量不会调用eists。但不建议使用global,应该避免使用global。你知道吗

我想你应该得到那个值而不是access变量,所以最好使用return语句 def编码器(输入文件): #一堆其他的代码 #更多的代码

    # 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)

相关问题 更多 >

    热门问题