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()

更多相关文章

  1. CDays -4 可用的首个Python脚本
  2. Python脚本——连接到SSH并运行命令
  3. 在python中复制命令的正确方法[复制]
  4. 毕业设计-基于深度神经网络的语音关键词检出系统-使用python脚本
  5. 转python爬虫:BeautifulSoup 使用select方法详解
  6. 如何按期执行python脚本?
  7. Python------类的结构细分,异常处理,方法,属性
  8. 【Python】Python脚本实现抢券
  9. 使用python 3.6将多个文件并行加载到内存中的最佳方法是什么?

随机推荐

  1. 红帽 redhat 更改yum源为本地光盘(cdrom)
  2. android连续调用setVisibility(View.VISI
  3. 从Gartner 最新“客户之选”报告,看国内外
  4. 懵逼树上懵逼果:学习二分搜索树
  5. Android(安卓)清单目录application对应属
  6. 【春节特辑】神奇的二进制
  7. 程序员群体的性取向如何?Stack Overflow
  8. 算法科普:神秘的 DES 加密算法
  9. 【春节特辑】三门问题
  10. 图解LeetCode第 103 号问题:二叉树的锯齿