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

问题描述 投票:1回答:2

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

我有一个python文件,其中包含以下声明: -

test1.朋友

print("this is test1")

test2.朋友

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

python subprocess jupyter-notebook scheduler apscheduler
2个回答
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将作为独立代码执行(即,您无法将变量传递给它)并且每次都将被读取和解析(在subprocess的情况下,每个也将生成一个新的Python进程)时间)。在第二种情况下,它将被读取一次并作为一个模块(即你可以将参数传递给test1.main())。


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()
© www.soinside.com 2019 - 2024. All rights reserved.