代码之家  ›  专栏  ›  技术社区  ›  Gunacelan M

使用python在Squish中导入文件

  •  2
  • Gunacelan M  · 技术社区  · 7 年前

    如果两个文件具有相同名称的函数,则在脚本中使用源(findFile())导入它们,并调用它以访问最后关联的文件中的函数。如何访问特定文件中的函数?squish with python是否支持导入文件语法?

    这是一个参考

    脚本1。py公司

    def runner1():
        test.log("Hey")
    

    def runner1():
        test.log("Bye")
    

    脚本:

    source(findFile("scripts","script_1.py"))
    source(findFile("scripts","script_2.py"))
    
    
    runner1()//function call
    

    订单:再见

    注意:当我使用文件名导入时,它会抛出错误“模块不存在”

    2 回复  |  直到 7 年前
        1
  •  2
  •   frog.ca    7 年前

    source() 使指定文件中的“符号”(函数、变量)加载到测试的命名空间/范围中。py文件。这意味着source()是解决此问题的错误工具。

    (我建议不要使用Orip显示的技巧,将函数分配给第一个源()之后的另一个符号/名称,因为依赖于在初始名称下可用的所需函数的其他代码最终会调用错误的函数。)

    sys.path :

    suite\u mine/tst\u testcase1/test的内容。py:

    # -*- coding: utf-8 -*-
    
    import os.path
    import sys
    
    # Add path to our modules to the Python search path at runtime:
    sys.path.append(os.path.dirname(findFile("scripts", "file1.py")))
    sys.path.append(os.path.dirname(findFile("scripts", "file2.py")))
    
    # Now import our modules:
    import file1
    import file2
    
    
    def main():
        # Access functions in our modules:
        file1.do_it()
        file2.do_it()
    

    suite\u mine/tst\u testcase1/file1的内容。py:

    # -*- coding: utf-8 -*-
    
    import test
    
    
    def do_it():
        test.log("file1.py")
    

    :

    # -*- coding: utf-8 -*-
    
    import test
    
    
    def do_it():
        test.log("file2.py")
    

    生成的日志条目:

    file1.py
    file2.py
    
        2
  •  1
  •   orip    4 年前

    当您逐个评估文件内容时:

    1. 第一个 source() 其中一个定义了“runner1”函数
    2. 第二个 来源() 使用新的“runner1”函数覆盖它

    squish docs 你可以 import 模块。您可能需要标记 scripts/ 通过在其中创建一个名为 __init__.py .

    然后你应该能够做到

    import scripts.script_1
    import scripts.script_2
    scripts.script_1.runner1()
    scripts.script_2.runner1()
    

    from scripts.script_1 import runner1 as foo1
    from scripts.script_2 import runner1 as foo2
    foo1()
    foo2()
    

    你甚至可以继续使用 来源() 通过保留对第一个的新引用 runner1 作用不过,这很粗糙,所以我更喜欢 进口 解决方案,如果你能使它工作。

    source(findFile("scripts","script_1.py"))
    foo = runner1
    source(findFile("scripts","script_2.py"))
    
    foo()     # runs runner1 from script_1
    runner1() # runs runner1 from script_2
    
    推荐文章