这是我的第一个 python (2.4)程序,我可以使用你的帮助。我有一个 csv 文件
HOST, PATH
server1, /path/to/file1.py
server2, /path/to/file2.py
server3, /path/to/file3.py
对列 2/row[1] 上的每个 PATH 执行命令
在命令的输出中,我搜索文本并将它们附加到新列中。
示例命令输出:
Command: python /path/to/file1.py
Output: server1 (NTFS) Reply:Yes
我想让我的新 csv 文件像:
HOST, PATH, PLATFORM, REPLY
server1, /path/to/file1.py, Windows, Yes
server2, /path/to/file2.py, Linux, Yes
server3, /path/to/file3.py, BSD, No
我还没有让它与读取相同的输出行并附加具有不同结果的两列一起工作。我曾尝试关闭作者并在同一个读者中打开一个新作者,但没有任何乐趣。我试过缩进没有运气。我得到的最接近的是让它准确地搜索两个字符串,但它只写入一列。
我也尝试过首先搜索 os 平台并将更改写入新文件然后,打开新文件以写入另一行
当然,我可以通过再次运行命令并单独搜索来强制它工作,但那是多余且不必要的。
import datetime
import csv
import os, time
from stat import * # ST_SIZE etc
from subprocess import Popen, PIPE, STDOUT
# Set Date
now = datetime.datetime.now()
today = now.strftime("%m-%d-%Y")
# Files
filename = "my_list.csv"
results = "results/results_" + today + ".csv" # Eg. results_04-14-2012.csv
# Commands
command = "python"
SP = " "
incsv = open(filename, 'rb')
try:
reader = csv.reader(incsv)
outcsv = open(results, 'w')
try:
writer = csv.writer(outcsv)
for row in reader:
p = Popen(command + SP + row[1], shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, empty = p.communicate()
print 'Command: %s\nOutput: %s\n' % (command + SP + row[1], stdout)
if not stdout:
writer.writerow(row + ['PLATFORM']) # Create header for new column when first line is empty on stdout
elif 'BSD' in stdout:
writer.writerow(row + ['BSD'])
elif 'Linux' in stdout or 'swap' in stdout or 'LLVM' in stdout or 'EBR' in stdout:
writer.writerow(row + ['Linux'])
elif 'NTFS' in stdout:
writer.writerow(row + ['Windows'])
else:
writer.writerow(row + ['Error Scanning'])
reply = open(results, 'w')
try:
writer = csv.writer(platform)
for row in reader:
if not stdout:
writer.writerow(row + ['REPLY']) # Create header for new column when first line is empty on stdout
elif 'Reply:Yes' in stdout:
writer.writerow(row + ['Yes'])
elif 'Reply:No' in stdout :
writer.writerow(row + ['No'])
else:
writer.writerow(row + ['Error'])
finally:
reply.close()
finally:
outcsv.close()
finally:
incsv.close()