【问题标题】:How to repeatedly run a python script from another python script?如何从另一个 python 脚本重复运行 python 脚本?
【发布时间】:2019-02-21 13:37:23
【问题描述】:

我想每隔 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 笔记本。 还尝试了子进程调用。

【问题讨论】:

  • 你试过 os.system('python test1.py') 吗?
  • 函数some_job() 导入模块,但实际上并不执行它们。要使用 os.system()subprocess 调用它们,您无需导入 test1 和 test2。

标签: python subprocess jupyter-notebook scheduler apscheduler


【解决方案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()

【讨论】:

    【解决方案2】:
    • 使用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>))
      

    • 将要执行的文件payload放入一个函数中,一次导入模块,反复调用函数:

      test1.py:

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

      主要代码:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-30
      • 2015-03-11
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多