用于运行其他Python脚本的Python脚本

时间:2014-05-14 22:31:17

标签: python timer

我有一个Python脚本,我试图编写以运行其他Python脚本。目标是能够让我一直运行的脚本在一夜之间执行我的其他脚本。 (我尝试使用批处理文件,它会执行它们,但由于某种原因它们不会创建.csv文件)这是我现在的代码。

import time
import subprocess
from threading import Timer

fileRan = False

#Function to launch other python files
def runFiles():

    print('Running Scripts Now')

    subprocess.call("cmd","report1.py",shell=True)
    subprocess.call("cmd","report2.py",shell=True)
    subprocess.call("cmd","report3.py",shell=True)
    subprocess.call("cmd","report4.py",shell=True)
    subprocess.call("cmd","report5.py",shell=True)
    subprocess.call("cmd","report6.py",shell=True)

#Function to check current system time against time reports should run
def checkTime(fileRan):
    startTime = '15:20'
    endTime = '15:25'

    print('Current Time Is: ', time.strftime('%H:%M', time.localtime()))

    print(fileRan)

    if startTime < time.strftime('%H:%M', time.localtime()) < endTime and fileRan is False:
        runFiles()
        fileRan = True

        return fileRan

#Timer itself
t = Timer(60.0, checkTime(fileRan))
t.start()

它将进行第一次传递并打印当前时间,并且fileRan的状态就好了。当我进行第二次检查或尝试执行文件时,它似乎会中断。这是我得到的错误:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 921, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 1187, in run
    self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

我能得到的任何帮助都会很棒!

2 个答案:

答案 0 :(得分:2)

您的subprocess.call()不正确,请在此处查看正确的语法:https://docs.python.org/2/library/subprocess.html

subprocess.call(["python", "report1.py"], shell=True)

还有其他工具可以帮助您,例如cron

答案 1 :(得分:2)

这不是您的问题的答案,而是编码建议。从其他Python脚本调用Python脚本应被视为最后的方法。

Answer to similar question

从Python文件调用Python文件的首选方法是将'reportsN.py'文件设计为可用作库和命令行可调用文件。 Python通过

支持这一点
if __name__ == "__main__":

成语。

ReportN.py将写成:

def stuff_to_do():
    pass

if __name__ == "__main__":
    stuff_to_do()

您的顶级脚本'run_files.py'会处理将每个'reportN.py'文件作为库导入,并根据需要将其stuff_to_do()函数/方法分配给线程。

这种方法并不总是可行的(例如,如果'reportN.py'不在您的控制之下),但这种方法可以通过从您必须应对的事物列表中取出“子进程”来简化您的问题。

相关问题