Search code examples
pythonsubprocessjupyter-notebookschedulerapscheduler

How to repeatedly run a python script from another python script?


I want to repeatedly run 2 python script every 10 seconds from another script.

I have a python file with the following statement:-

test1.py

print("this is test1")

test2.py

print("this is test2")

main code

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

The result I get is as follows Output

I actually want it to print as

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

and so on every 10 second.

I tried using os.system('test1.py') but it opens the file in pycharm. Im using jupyter notebook. also tried subprocess call.


Solution

    • Either use runpy.run_path or subprocess.check_call to run the file as a script:

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

      or

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

      or

    • Put the file's payload to be executed into a function, import the module once and invoke the function repeatedly:

      test1.py:

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

      main code:

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

    The main difference is that in the first case, test1.py will be executed as standalone code (i.e. you cannot pass variables to it) and will be read and parsed each time (in the case of subprocess, a new Python process will also be spawned each time). While in the 2nd case, it will be read once and as a module (i.e. you can pass arguments to test1.main()).