【问题标题】:Python Script to run other Python Scripts运行其他 Python 脚本的 Python 脚本
【发布时间】:2014-05-14 22:31:17
【问题描述】:

我有一个 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

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

【问题讨论】:

  • 对于初学者,将行 t = Timer(60.0, checkTime(fileRan)) 更改为 t = Timer(60.0, checkTime, fileRan) (因为计时器必须调用函数本身,而您调用函数然后传递结果)
  • 按照t = Timer(60.0, checkTime,fileRan) 的建议进行更改现在收到此错误。 TypeError: checkTime() argument after * must be a sequence, not bool
  • 试试t = Timer(60.0, checkTime, [fileRan]),并在我的回答中查看编辑。
  • 简单解决方法请参考以下链接simple solution using os.system in python

标签: python timer


【解决方案1】:

这不是您的问题的答案,而是编码建议。从其他 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”不在您的控制之下),但这种方法可以通过将“子流程”从您必须处理的事情列表中删除来简化您的问题。

【讨论】:

    【解决方案2】:

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

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

    还有其他工具可以为您执行此操作,例如 cron

    【讨论】:

    • “python”和“report1.py”之间应该有一个空格。
    • @ZeeshanMahmood,不应该有空格。 subprocess.call 接受命令及其参数的列表或将它们全部放在一起的单个字符串。如果您传递一个列表,它会自动添加空格。阅读我在答案中链接到的文档。
    • 你是对的。我错过了注意到它是一个列表。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 2010-11-24
    • 2023-03-13
    相关资源
    最近更新 更多