从另一个Python脚本调用Python脚本的最佳方式是什么?
16lz
2021-01-22
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的脚本。它不在模块中。它只有运行脚本时应该执行的代码。没有函数、类、方法等等。我有另一个脚本作为服务运行。我想调用test1。py来自作为服务运行的脚本。
For example:
例如:
File test1.py
print "I am a test"
print "see! I do nothing productive."
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 eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.
我知道有一种方法是打开文件,读取内容,并基本上eval它。我假设有更好的方法。至少我希望如此。
8 个解决方案
#1
204
The usual way to do this is something like the following.
通常的做法是这样的。
test1.py
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
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()
更多相关文章
- CDays -4 可用的首个Python脚本
- Python脚本——连接到SSH并运行命令
- 在python中复制命令的正确方法[复制]
- 毕业设计-基于深度神经网络的语音关键词检出系统-使用python脚本
- 转python爬虫:BeautifulSoup 使用select方法详解
- 如何按期执行python脚本?
- Python------类的结构细分,异常处理,方法,属性
- 【Python】Python脚本实现抢券
- 使用python 3.6将多个文件并行加载到内存中的最佳方法是什么?