簡體   English   中英

為 Windows 執行多個 python 文件的腳本

[英]Script to execute multiple python files for Windows

我有一個 python 腳本 (script.py),每個輸入 (input.txt) 需要一個文件,每個輸出 (output.txt) 需要一個文件。 另外,腳本需要來自model.pcl 的額外數據。 我通過控制台執行腳本。 對於 Windows,它看起來像這樣:

輸入 input.txt | python script.py model.pcl output.txt

我想將此腳本應用於 10,000 個文件並將結果保存在單獨的 txt 文件中。

我知道如何用 python 做到這一點:

import subprocess
for i in range(1, 10001):
    e = 'type input_%s.txt | python script.py model.pcl output/output_%s.txt' % (i,i)
    subprocess.call(e, shell=True)

但這不是一個理想的解決方案,因為在這種方法中我無法為輸入文件 (input/input_%s.txt) 指定文件夾。 如果我嘗試這樣做,我會收到一個錯誤:

the syntax of the command is incorrect.

Windows 機器還有其他選擇嗎?

我在 python 中遇到過類似的問題。 當我將所有項目添加到列表中時,它對我有用。

import subprocess 
for i in range(1, 10001): 
    e = ['type input_%s.txt | python script.py model.pcl output/output_%s.txt' % (i,i)]
    subprocess.call(e, shell=True)

你能測試一下,讓我知道它是否適合你嗎?

這應該從 Windows CMD 提示中完成所需的操作:

FOR /L %# IN (1,1,10001) DO @TYPE "C:\Path\To\input_%#.txt"   | python script.py model.pcl "C:\Path\To\output_%#.txt"

一種選擇與此類似

#Path to all files
path = os.getcwd()
#Puts file names to a variable
files = os.listdir(path)
#Gets just the .txt
txtFiles = glob.glob(path + "/*.txt")

這將允許您在特定文件夾中執行所有 .txt 文件,理想情況下是放置腳本但可以輕松修改的文件夾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM