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
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.
The easiest way is to define functions in those .py files. Change test.py1 to:
def test1():
print("this is test 1")
And change test2.py to:
def test2():
print("this is test 2")
Than change your main code to:
from test1 import test1
from test2 import test2
def some_job():
print('hello')
test1()
test2()
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 (ie 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 (ie you can pass arguments to test1.main()
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.