0

いくつかの入力を受け取り、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

何かご意見は?

4

1 に答える 1

1

Pythonで「grep」タスクを直接実行する方が簡単で高速です。

with open("filename") as f:
    for line in f:
        if "foo" in line:
           ... # do something to handle the case of "foo" in line

これが「dax」と呼ばれるホストを追加するプログラムです/etc/hosts

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")

2つのファイル名を指定すると、出力ファイル名はのコピーを取得します/etc/hosts。システム名「dax」がすでににある/etc/hosts場合、コピーは正確になります。それ以外の場合は、行が追加されます。

正規表現を使用して特定の行を検出することでこのアイデアを拡張できます。また、元の行の代わりに別の行を書き込むことで行を編集できます。

このプログラムは、正規表現を使用して、からまで/etc/hostsの範囲にあるファイル内のすべてのエントリを検索します。これらの行は、変更されずに元のアドレスである場所に移動するように書き直されます。192.168.0.10192.168.0.59192.168.1.**

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)

出力ファイルの書き込みに成功し、エラーが発生しなかった場合は、を使用os.rename()して新しいファイルの名前を元のファイル名に変更し、古いファイルを上書きすることができます。古いファイルの行を変更する必要がないことがわかった場合は、名前を変更する代わりに、新しいファイルを削除するだけで済みます。常に名前を変更すると、実際には何も変更していなくても、ファイルの変更タイムスタンプが更新されます。

編集:これは最後のコードサンプルを実行する例です。コードをと呼ばれるファイルに入れて、move_subnet.pyLinuxまたは他の* NIXで、次のように実行できるとします。

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

Windowsを使用している場合は、次のようになります。

python move_subnet.py C:/Windows/system32/drivers/etc/hosts ./hosts_copy.txt

Windowsは、ファイル名に円記号またはスラッシュを使用できることに注意してください。この例ではスラッシュを使用しました。

出力ファイルはhosts_copy.txt現在のディレクトリにあります。

于 2012-06-25T19:36:58.753 に答える