2012-06-25 2 views
0

나는 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 

의견이 있으십니까?

+1

[동일한 줄에 여러 개의 가져 오기를 넣지 않는 것이 좋습니다.] (http://www.python.org/dev/peps/pep-0008/#imports) – moooeeeep

+0

이유가 있습니다. 나는 파이썬을 처음 접했을뿐입니다. – MHibbin

+1

@moooeeeep은 클릭 할 수있는 링크에 대한 전체적인 댓글을 남겼습니다. 그것을 클릭하면 웹 페이지로 이동하게되고, 그 웹 페이지는 그 이유를 설명합니다. – steveha

답변

1

그것은 쉬울 것, 빠르고, 직접 파이썬에서 "GREP"작업을 수행 :

import sys 
_, in_fname, out_fname = sys.argv 

found_in_file = False 
with open(in_fname) as in_f, open(out_fname, "w") as out_f: 
    for line in lst: 
     if line.endswith("dax"): 
      found_in_file = True 
     out_f.write(line) 
    if not found_in_file: 
     out_f.write("192.168.0.199\tdax\n") 
: 여기
with open("filename") as f: 
    for line in f: 
     if "foo" in line: 
      ... # do something to handle the case of "foo" in line 

/etc/hosts에 "DAX"라는 호스트를 추가하는 프로그램입니다

두 개의 파일 이름을 지정하면 출력 파일 이름은 /etc/hosts이됩니다. 시스템 이름 "dax"가 이미 /etc/hosts에 있으면 사본이 정확합니다. 그렇지 않으면 라인이 추가됩니다.

일반 표현식을 사용하여 특정 줄을 검색하여이 아이디어를 확장 할 수 있으며 원본 대신 다른 줄을 작성하여 줄을 편집 할 수 있습니다.

이 프로그램은 /etc/hosts 파일의 모든 항목이 192.168.0.10에서 192.168.0.59까지의 범위에있는 정규식을 사용합니다. 해당 행은 다시 192.168.1.*으로 옮겨지며 *은 원래 주소로 변경되지 않습니다. 성공적으로 출력 파일을 작성했습니다, 그리고 오류가 당신이 때문에 이전 파일을 덮어 쓰기, 원본 파일 이름에 새 파일의 이름을 변경 os.rename()을 사용할 수 없었다

import re 
import sys 
_, in_fname, out_fname = sys.argv 

pat = re.compile(r'^192.168.0.(\d+)\s+(\S+)') 

with open(in_fname) as in_f, open(out_fname, "w") as out_f: 
    for line in in_f: 
     m = pat.search(line) 
     if m: 
      x = int(m.group(1)) 
      if 10 <= x < 60: 
       line = "192.168.1." + str(x) + "\t" + m.group(2) + "\n" 
     out_f.write(line) 

. 이전 파일의 행을 변경하지 않아도된다고 판단되면 새 파일을 이름 바꾸기 대신 삭제할 수 있습니다. 항상 이름을 바꾸면 실제로 변경하지 않았더라도 파일의 수정 타임 스탬프를 업데이트하게됩니다.

편집 : 다음은 마지막 코드 샘플을 실행 한 예입니다.

python move_subnet.py C:/Windows/system32/drivers/etc/hosts ./hosts_copy.txt 
: Windows를 사용하는 경우

python move_subnet.py /etc/hosts ./hosts_copy.txt 

, 그것은 이런 식으로 뭔가있을 것 : 말 당신은 다음과 같이 실행할 수 있습니다 리눅스 또는 다른 * NIX에 다음 move_subnet.py라는 파일에 코드를 삽입

Windows는 파일 이름에 백 슬래시 또는 슬래시를 사용할 수 있습니다. 이 예제에서는 슬래시를 사용했습니다.

출력 파일은 현재 디렉토리에 hosts_copy.txt이됩니다.

+0

안녕하세요 steveha, 빠른 응답을 보내 주셔서 감사합니다. 저는이 작업 방식이 약간 혼란 스럽습니다. 파일에 코드를 작성하고 테스트 해 보았습니다. 그러나 존재하지 않는 파일에 오류가 있습니다. -S – MHibbin

+0

@MHibbin 코드 스 니펫을 상황에 맞게 적용하려고 했습니까? – moooeeeep

+0

@moooeeeep & @steveha, 나는 위의 대답에서 일하려고하는 코드를 업데이트했습니다. os.rename 부분에 문제가 있습니다. 'import os' 'import sys' 'in_file = "inFile.txt" – MHibbin