我对 python 完全陌生,我读过 python 的 csv 模块非常适合我想做的事情。我花了一些时间尝试几种不同的方法,但还不能使用第四(垂直)列创建数组。
我有一个包含数百行的四列 csv 文件。在我继续之前,我可能应该验证 python 甚至可以完成我想做的所有事情。
- 读取 csv 文件,
在 FILE 的第四(垂直)列上执行 COMMAND
命令打印
阅读健康的每一行(来自命令)
将新的第五列上的 HEALTHY 写入所有五列的 NEW_FILE
- 循环直到 FILE 的第一个空行
示例文件(在单元格视图中以逗号分隔)
HOST PLATFORM ARCH COMMAND
server1 win x86_64 python '/root/server1.py'
server2 linux x86_64 python '/root/server2.py'
server3 linux x86_64 python '/root/server3.py'
示例命令
# python '/root/server1.py'
--------------------
Error: Could not open /root/server1.py
# python '/root/server2.py'
--------------------
server2 p1 (NTFS) output1:100 output:200 HEALTHY:Yes
--------------------
# python 'root/server3.py'
--------------------
server3 p1 (linux) output1:100 output:200 HEALTHY:No
server3 p2 (linux) output1:100 output:200 HEALTHY:Yes
server3 p3 (swap) output1:100 output:200 HEALTHY:No
--------------------
如果多行 HEALTHY 和 all 不等于 Yes,HEALTHY 等于“No”
如果在任何行上都找不到 HEALTHY,则 HEALTHY 等于“错误扫描”
这是我到目前为止所拥有的
#!/usr/bin/python
#
import csv
import subprocess
# read csv file
csv_file = open("my_list.csv", "rb")
my_csv_reader = csv.reader(csv_file, delimiter=",")
my_data_list = []
for row in my_csv_reader:
print row
my_data_list.append(row)
csv_file.close()
# write csv file
csv_file = open("new_data.csv", "wb")
my_csv_writer = csv.writer(csv_file, delimiter=",")
for row in my_data_list:
my_csv_writer.writerow(row)
csv_file.close()
# running commands, getting output
# run COMMAND column from csv_file, use "python 'my_script.py'" for now
# my_script.py only for now: print "HEALTHY:Yes"
p = subprocess.Popen("python '/root/my_script.py'",stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output, errors = p.communicate()
print output
print errors
执行上述:
# python '/root/this_script.py'
['HOST', 'PLATFORM', 'ARCH', 'COMMAND']
['server1', 'win', 'x86_64', "python '/root/server1.py'"]
['server2', 'linux', 'x86_64', "python '/root/server2.py'"]
['server3', 'linux', 'x86_64', "python '/root/server3.py'"]
Traceback (most recent call last):
File "thisscript.py", line 24, in ?
p = subprocess.Popen('python myscript1.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE)
File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__
errread, errwrite)
File "/usr/lib64/python2.4/subprocess.py", line 993, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
奖励:
如果我还想在标准输出/命令输出中搜索某些内容(例如 linux、swap、NTFS 等,--第三个上面有问题的示例命令)并将其附加到第 [5] 行,或者在它已经存在之后的下一个搜索 [i]Healthy[/i]... 我尝试开始一个新的 if 语句,但它似乎只追加行 [4],或与 [i]Healthy[/i] 时相同的行。
我也不知道如何使用 OR 语句。在哪里
if 'Linux' OR 'swap' OR 'LVM' in stdout:
writer.writerow(row + ['Linux']) # for multiple lines/partitions.
elif 'BSD' in stdout:
writer.writerow(row + ['BSD'])
elif 'NTFS' in stdout:
writer.writerow(row + ['Windows'])
else:
writer.writerow(row + ['Error Scanning'])
最后,我将 COMMAND 列更改为 PATH,并修改了执行 PATH 的命令。哪个正在工作。我想执行第二个命令来获取 PATH 的文件大小。我尝试了几种方法。
感谢您的时间。我希望这一切都能做到。