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

Python 如何访问函数中声明的变量?,python,function,variables,python-3.6,Python,Function,Variables,Python 3.6,我有以下代码: 脚本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 _

我有以下代码:

脚本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_location。因此,我可以告诉script2在何处查找它试图处理的文件,而无需硬编码

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

NameError: name 'conv_output_file' is not defined

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

告诉第二个剧本

您必须正确地
将第一个脚本导入第二个脚本,并使用
编码器
功能作为第一个脚本的属性

例如,命名您的第一个脚本
encoder\u script
。 在第二个脚本中

import encoder_script
encoder_script.encode(filename)

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

返回它或使其成为全局变量,然后导入它


可能您在正确导入它时遇到了一些困难

明确这两点:

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

  • 您实际想要对变量conv_output_文件做什么?如果您只想获取conv_output_文件绑定到的值/对象,那么最好使用return语句。或者,如果您希望访问该变量并对该变量执行更多操作,即修改它,那么您可以使用global访问变量conv_output_文件

    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_文件的形式访问变量,因为在函数未被调用之前,变量不会执行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)
    

    为什么不能在函数中
    返回conv_output_file
    ?每种方法都有什么问题/错误?添加更多您尝试过的代码far@idjaw我已经试过了,但是我仍然发现,
    conv\u output\u文件未定义错误。
    @EliC那么您在导入和运行代码方面做得不对。您需要更好地展示您的问题,以帮助读者更好地了解您面临的问题。@idjaw我已经了解了问题的一部分。我使用
    subprocess.run()
    来运行一个terminal命令,我在这之后声明了变量,因为我认为它在那里是必需的,但事实证明它是必需的。在向上移动后,我现在在调试步骤过程中看到它被设置为正确的字符串值,但由于某些原因,导入失败。我已经用上面的更多信息更新了这个问题。