繁体   English   中英

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

[英]How to repeatedly run a python script from another python script?

我想每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()

我得到的结果如下 产量

我实际上希望它打印为

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笔记本。 还尝试了子流程调用。

最简单的方法是在这些.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()
  • 无论是使用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将作为独立代码执行(即,您不能将变量传递给它),并且每次都将被读取和解析(对于subprocess进程,还将创建一个新的Python进程)。每次生成)。 test1.main()情况下,它将作为模块读取一次(即,您可以将参数传递给test1.main() )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM