【问题标题】:I have two scripts of code and i want to import just one specific line from one into the other. How do i do it?我有两个代码脚本,我只想将一个特定的行从一个导入到另一个。我该怎么做?
【发布时间】:2023-03-14 18:09:01
【问题描述】:

我想将一个特定的代码行从一个脚本导入到另一个。我不希望新代码仅在一行中运行整个脚本。我该怎么做?

例如from brcus import value

其中 value 等于已完成脚本中的一个数字,我想将该数字导入新脚本中,旧脚本中的那行代码是:“value=500”

【问题讨论】:

    标签: python python-3.x python-2.7 import


    【解决方案1】:

    我不推荐您提取变量的方法。相反,您应该查看实际的数据交换格式,例如jsonxml。 这些旨在为程序保存和制作可访问的键值对,同时(在某种程度上)人类可读。 这些格式的解析器以及更多可用的解析器。

    【讨论】:

      【解决方案2】:

      每当您导入任何 python 模块或包并使用该模块中的某些函数或值时,它都不会一次运行所有脚本。

      你可以这样做。

      1. 新脚本:-new.py
      2. 旧脚本:- old.py

      如果它在同一个目录中..

      from old import value
      
      a = value
      

      【讨论】:

      • 你能把你的2个脚本贴在这里,以便我们分析并帮助你
      【解决方案3】:

      我建议将您要导入的部分移到单独的模块中,并将其导入到它使用的所有模块中

      my_var.py

       text = "Hello"
      

      test.py

      from my_var import text
      
      def hello_friend(friend_name)
          print(text + " " + friend_name)
      
      

      main.py

      from my_var import text
      
      print(text)
      

      您还可以设置一个环境变量并在您要导入的模块中检查它的值

      test.py

      import os
      
      if os.environ['only_new_str'] != str(True):
          print("new_str is not calculated yet")
      new_str = "Hello world"
      if os.environ['only_new_str'] != str(True):
          print("new_str calculated")
      

      main.py

      import os
      os.environ['only_new_str'] = str(True)
      import test
      
      print(test.new_str)
      

      【讨论】:

        【解决方案4】:

        如果你使用命令导入

        from package import value
        

        价值将作为新代码的一部分出现在您的新代码中

        例如

        来源.py

        value = 500
        other = 400
        

        命运.py

        from Source import value
        print (value)
        >>500
        

        命运.py

        from Source import value
        print (other)
        >>NameError: name 'other' is not defined
        

        【讨论】:

          猜你喜欢
          • 2019-02-05
          • 1970-01-01
          • 2023-02-03
          • 1970-01-01
          • 2013-10-16
          • 1970-01-01
          • 1970-01-01
          • 2017-10-31
          • 2019-10-19
          相关资源
          最近更新 更多