【发布时间】:2018-02-06 17:22:48
【问题描述】:
我有许多 python 脚本,通过单击它们单独运行每个脚本很痛苦。如何制作一个批处理文件来一次运行它们?
【问题讨论】:
-
你的环境是什么?
标签: python batch-file
我有许多 python 脚本,通过单击它们单独运行每个脚本很痛苦。如何制作一个批处理文件来一次运行它们?
【问题讨论】:
标签: python batch-file
只需制作一个像这样的脚本来处理每个任务(在 Windows 上):
start /B python script1.py
start /B python script2.py
start /B python script3.py
在 *nix 上:
python script1.py &
python script2.py &
python script3.py &
假设您的脚本不需要人工交互才能运行
【讨论】:
使用start 命令启动进程。
@echo off
start "" foo.py
start "" bar.py
start "" baz.py
重新评论:“有没有办法让这些最小化?”
您始终可以通过键入命令名称和/? 来询问命令的工作原理。在这种情况下,start /? 告诉我们它的命令行选项包括:
MIN Start window minimized.
因此,要最小化启动应用程序,请使用:
start "" /MIN quux.py
【讨论】:
根据需要同时运行尽可能多的 .py 文件。为每个 .py 创建一个 .bat 以启动 python 文件。定义列表列表中的所有 .bat 文件。列表中的第二个参数是启动 .bat 文件的延迟。不要使用零来表示延迟。它工作正常。通过这种方式,您将并行性留给了非常快速且稳定的操作系统。对于您启动的每个 .bat,都会打开一个命令窗口以与用户进行交互。
from apscheduler.schedulers.background import BackgroundScheduler
import datetime as dt
from os import system
from time import sleep
parallel_tasks = [["Drive:\YourPath\First.bat", 1], ["Drive:\YourPath\Second.bat", 3]]
def DatTijd():
Nu = dt.datetime.now()
return Nu
def GetStartTime(Nu, seconds):
StartTime = (Nu + dt.timedelta(seconds=seconds)).strftime("%Y-%m-%d %H:%M:%S")
return StartTime
len_li = len(parallel_tasks)
sleepTime = parallel_tasks[len_li - 1][1] + 3
Nu = DatTijd()
for x in range(0, len_li):
parallel_tasks[x][0] = 'start cmd /C ' + parallel_tasks[x][0]
# if you want the command window stay open after the tasks are finished use: cmd /k in the line above
delta = parallel_tasks[x][1]
parallel_tasks[x][1] = GetStartTime(Nu, delta)
JobShedul = BackgroundScheduler()
JobShedul.start()
for x in range(0, len_li):
JobShedul.add_job(system, 'date', run_date=parallel_tasks[x][1], misfire_grace_time=3, args=[parallel_tasks[x][0]])
sleep(sleepTime)
JobShedul.shutdown()
exit()
echo off
Title Python is running [Your Python Name]
cls
echo "[Your Python Name] is starting up ..."
cd Drive:\YourPathToPythonFile
python YourPyFile.py
【讨论】: