运行其他Python脚本的Python脚本

1 投票
2 回答
3702 浏览
提问于 2025-04-18 06:36

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

这个脚本第一次运行时会打印当前时间和文件状态,看起来一切正常。但是在进行第二次检查时,或者在尝试执行文件时就出问题了。这里是我遇到的错误:

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 个回答

2

你的 subprocess.call() 用法不对,正确的写法可以在这里查看: https://docs.python.org/2/library/subprocess.html

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

还有其他工具可以帮你完成这个任务,比如 cron

2

这不是解决你问题的答案,而是一个编程建议。从一个Python脚本调用另一个Python脚本应该是最后的选择。

类似问题的回答

从一个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'不在你的控制之下),但这样做可以简化你的问题,因为你不需要再处理'subprocess'相关的内容。

撰写回答