Python-从另一个脚本调用一个脚本的最佳方法是什么?

发布于 2021-02-02 23:21:27

我有一个名为test1.py的脚本,该脚本不在模块中。它只包含应在脚本本身运行时执行的代码。没有函数,类,方法等。我有另一个作为服务运行的脚本。我想从作为服务运行的脚本中调用test1.py。

例如:

文件test1.py
print "I am a test"
print "see! I do nothing productive."

文件service.py

# Lots of stuff here
test1.py # do whatever is in test1.py

我知道一种方法是打开文件,读取内容并进行基本评估。我假设有一种更好的方法。或者至少我希望如此。

关注者
0
被浏览
114
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    这样做的通常方法如下。

    test1.py

    def some_func():
        print 'in test 1, unproductive'
    
    if __name__ == '__main__':
        # test1.py executed as script
        # do something
        some_func()
    

    service.py

    import test1
    
    def service_func():
        print 'service func'
    
    if __name__ == '__main__':
        # service.py executed as script
        # do something
        service_func()
        test1.some_func()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看