如何从另一个python脚本重复运行python脚本?

时间:2019-02-21 13:37:24

标签: python subprocess jupyter-notebook scheduler apscheduler

我想每10秒从另一个脚本重复运行2个python脚本。

我有一个带以下语句的python文件:-

test1.py

print("this is test1")

test2.py

print("this is test2")

主要代码

from apscheduler.schedulers.blocking import BlockingScheduler


def some_job():
    print('hello')
    import test1
    import test2

scheduler = BlockingScheduler()
job=scheduler.add_job(some_job, 'interval', seconds=10)
scheduler.start()

我得到的结果如下 Output

我实际上希望它打印为

hello
this is test1
this is test2
hello
this is test1
this is test2
hello
this is test1
this is test2

以此类推,每隔10秒。

我尝试使用os.system('test1.py'),但它会在pycharm中打开文件。我正在使用jupyter笔记本。 还尝试了子流程调用。

2 个答案:

答案 0 :(得分:1)

最简单的方法是在这些.py文件中定义函数。将test.py1更改为:

 def test1():
      print("this is test 1")

并将test2.py更改为:

def test2():
       print("this is test 2")

比将您的主要代码更改为:

 from test1 import test1
 from test2 import test2

 def some_job():
     print('hello')
     test1()
     test2()

答案 1 :(得分:1)

  • 使用runpy.run_pathsubprocess.check_call作为脚本运行文件:

    import runpy
    def some_job():
        <...>
        runpy.run_path('test1.py')
    

    import sys, subprocess
    def some_job():
        <...>
        subprocess.check_call((sys.executable, 'test1.py', <command line args if needed>))
    

  • 将要执行的文件有效负载放入函数中,一次导入模块并重复调用该函数:

    test1.py:

    def main():
        print("this is test1")
    

    主要代码:

    import test1
    
    def some_job():
        <...>
        test1.main()
    

主要区别在于,在第一种情况下,test1.py将作为独立代码执行(即,您不能将变量传递给它),并且每次都会被读取和解析(对于{{1}而言) },每次也会产生一个新的Python进程)。在第二种情况下,它将作为模块读取一次(即,您可以将参数传递给subprocess)。

相关问题