나는 sys.argv에 따라 파일에 입력을 넣는 다음과 같은 파이썬 스크립트를 가지고있다. 일부 중복 항목 검사를 추가하고 싶습니다 ... 값이 sys.argv를 통해 파일로 전달되었지만 이미 존재하지 않는 경우, 파일에 행을 인쇄하십시오.if 문처럼 파이썬 grep
서브 프로세스와 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")
업데이트 : 나는, 나는 os.rename 부분에 문제가 steveha에 의해 제공되는 기반으로 불리는 작은 조각을 시도하고
>>> 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))
에있는 I 다음 오류가 발생합니다.
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
의견이 있으십니까?
[동일한 줄에 여러 개의 가져 오기를 넣지 않는 것이 좋습니다.] (http://www.python.org/dev/peps/pep-0008/#imports) – moooeeeep
이유가 있습니다. 나는 파이썬을 처음 접했을뿐입니다. – MHibbin
@moooeeeep은 클릭 할 수있는 링크에 대한 전체적인 댓글을 남겼습니다. 그것을 클릭하면 웹 페이지로 이동하게되고, 그 웹 페이지는 그 이유를 설명합니다. – steveha