【问题标题】:Getting command line output of batch file to write to another file获取批处理文件的命令行输出以写入另一个文件
【发布时间】:2026-01-06 03:30:01
【问题描述】:

我有一个调用批处理文件的 python 文件。批处理文件写入命令行窗口。如何从 python 文件中的批处理文件将该输出解析到命令行。

我得到的唯一输出是NONENONE

import csv
import os
import subprocess

def callGetDimmBatchFile(goodFile, badFile, logFile, batchFileName, ipAddress, userName, passWord):
        command ='{0} -i {1} -u {2} -p {3}'.format(batchFileName, ipAddress, userName, passWord)
        print(command)
        logFile.write(command + '\n')
        logFile.flush()
        p = subprocess.Popen(command)
        output = p.communicate()
        logFile.write('{0}'.format(output) + '\n')
        logFile.flush()

goodFile = open('good.txt', 'w+')
badFile = open('bad.txt', 'w+')
logFile = open('log.txt', 'w+')
batchFileName = 'getdimm.bat'
pathToCsv = 'autorun-input.csv'
print('Path to CSV is {0}'.format(pathToCsv))
counter = 0
with open(pathToCsv) as csvFile:
    reader = csv.reader(csvFile, delimiter=',')
    for row in reader:
        ipAddress = row[0]
        userName = row[1]
        passWord = row[2]
        counter += 1
        print(counter)
        logFile.write('{0}'.format(counter) + '\n')
        logFile.flush()
        callGetDimmBatchFile(goodFile, badFile, logFile, batchFileName, ipAddress, userName, passWord)

os.system("pause")

【问题讨论】:

  • 看起来您可能想要p = subprocess.Popen(command, stdout=logFile, stderr=logFile); rc = p.wait(); print('\nReturn Code:', rc, file=logFile, flush=True) 之类的东西。

标签: python windows batch-file python-3.x


【解决方案1】:

也许为此使用命令模块而不是子进程?它会给你命令的结果

import commands
result = commands.getoutput('ls')
print(result)

【讨论】:

  • 我无法使用commands,因为我使用的是 Python 版本 3
最近更新 更多