いくつかの入力を受け取り、sys.argv に応じてそれらをファイルに入れる次の python スクリプトがあります。重複エントリのチェックを追加したい...値がsys.argvを介して渡されてファイルに入れられたが、それがすでに存在する場合と同様に、何もせずに行をファイルに出力します。
サブプロセスでこれを行い、システムの find/grep コマンド (それぞれ Windows/Linux 用) を使用することを考えていましたが、このテストを機能させることができません。
どんな考え/コードも歓迎します。
ありがとう
# Import Modules for script
import os, sys, fileinput, platform, subprocess
# Global variables
hostsFile = "hosts.txt"
hostsLookFile = "hosts.csv"
hostsURLFileLoc = "urls.conf"
# Determine platform
plat = platform.system()
if plat == "Windows":
# Define Variables based on Windows and process
#currentDir = os.getcwd()
currentDir = "C:\\Program Files\\Splunk\\etc\\apps\\foo\\bin"
hostsFileLoc = currentDir + "\\" + hostsFile
hostsLookFileLoc = currentDir + "\\..\\lookups\\" + hostsLookFile
hostsURLFileLoc = currentDir + "\\..\\default\\" + hostsURLFileLoc
hostIP = sys.argv[1]
hostName = sys.argv[2]
hostURL = sys.argv[3]
hostMan = sys.argv[4]
hostModel = sys.argv[5]
hostDC = sys.argv[6]
# Add ipAddress to the hosts file for python to process
with open(hostsFileLoc,'a') as hostsFilePython:
# print "Adding ipAddress: " + hostIP + " to file for ping testing"
# print "Adding details: " + hostIP + "," + hostName + "," + hostURL + "," + hostMan + "," + hostModel + " to file"
hostsFilePython.write(hostIP + "\n")
# Add all details to the lookup file for displaying on-screen and added value
with open(hostsLookFileLoc,'a') as hostsLookFileCSV:
hostsLookFileCSV.write(hostIP + "," + hostName + "," + hostURL + "," + hostMan + "," + hostModel + "," + hostDC +"\n")
if hostURL != "*":
with open(hostsURLFileLoc,'a+') as hostsURLPython:
hostsURLPython.write("[" + hostName + "]\n" + "ping_url = " + hostURL + "\n")
更新: steveha によって提供されたものに基づいて、呼び出された小さなスニペットを試しています。os.rename 部分に問題があります。
>>> import os
>>> import sys
>>> in_file = "inFile.txt"
>>> out_file = "outFile.txt"
>>> dir = "C:\\Python27\\"
>>> found_in_file = False
>>> with open(in_file) as in_f, open(out_file,"w") as out_f:
... for line in in_f:
... if line.endswith("dax"):
... found_in_file = True
... if not found_in_file:
... out_f.write("192.168.0.199\tdax\n")
... os.rename( os.path.join(dir, in_f), os.path.join(dir,out_f))
次のエラーが表示されます。
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "C:\Python27\lib\ntpath.py", line 73, in join
elif isabs(b):
File "C:\Python27\lib\ntpath.py", line 57, in isabs
s = splitdrive(s)[1]
File "C:\Python27\lib\ntpath.py", line 125, in splitdrive
if p[1:2] == ':':
TypeError: 'file' object is not subscriptable
何かご意見は?