从另一个脚本调用脚本的最佳方法是什么? [英] What is the best way to call a script from another script?

查看:44
本文介绍了从另一个脚本调用脚本的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.

例如:

文件test1.py:

File test1.py:

print "I am a test"
print "see! I do nothing productive."

文件service.py:

File service.py:

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

我知道一种方法是打开文件、读取内容并对其进行基本评估.我假设有更好的方法来做到这一点.或者至少我希望如此.

I'm aware of one method which is opening the file, reading the contents, and basically evaluating it. I'm assuming there's a better way of doing this. Or at least I hope so.

推荐答案

通常的方法如下所示.

test1.py

def some_func():
    print 'in test 1, unproductive'

if __name__ == '__main__':
    # test1.py executed as script
    # do something
    some_func()

服务.py

import test1

def service_func():
    print 'service func'

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

这篇关于从另一个脚本调用脚本的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆