简体   繁体   English

python文件完成后如何运行另一个python文件

[英]How to run another python file when a python file is finished

For example, I have two python file test1.py and test2.py. 例如,我有两个python文件test1.py和test2.py。 At first, test1.py will run. 首先,将运行test1.py。 And I want test2.py to be run when the test1.py is finished. 我希望在test1.py完成时运行test2.py。

I want the two python files run in different shell. 我希望两个python文件在不同的shell中运行。 That means test1.py should be closed when it is finished. 这意味着test1.py应​​该在完成时关闭。

All the help is appreciated! 感谢所有的帮助! Thank you! 谢谢!


I want this task to be some kind of scheduler task. 我希望此任务是某种调度程序任务。 At 12:00 pm the test1.py is executed. 在下午12:00执行test1.py。 And after test1.py is finished, I want to execute test2.py automatically 在test1.py完成后,我想自动执行test2.py

一旦第一个脚本用atexit完成,您就可以使用shutdown钩子来执行其他脚本

atexit.register(lambda: execfile('other.py')) # pass function to execute other file

The easiest way is going to be to do this in the shell, not using pure python. 最简单的方法是在外壳中执行此操作,而不是使用纯python。 Just run python test1.py && python test2.py or python test1.py; python test2.py 只需运行python test1.py && python test2.pypython test1.py; python test2.py python test1.py; python test2.py . python test1.py; python test2.py

The one with && won't run test2.py if test1 fails while the one using ; 如果test1失败,则带有&&的那个不会运行test2.py,而使用;的那个会运行; will run both regardless. 无论如何都将运行。

Consider there are three files. 考虑有三个文件。 one.py is your task one, two.py is your task two and main.py is your main file which calls the other two tasks. one.py是您的任务一,two.py是您的任务二,main.py是您的主文件,它调用了另外两个任务。

You can have your code something like this. 您可以使代码像这样。

one.py 一个

import time

class One():
    print "Before sleep one"
    time.sleep(5)
    print "After sleep one"

two.py py

import time

class Two():
    print "Before sleep two"
    time.sleep(5)
    print "After sleep two"

main.py main.py

from one import One
from two import Two

One()
Two()

Output 输出量

python main.py
Before sleep one
After sleep one
Before sleep two
After sleep two

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

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