Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sub command
#1
sub.py is my "sub" command. it substitutes one string (arg 2) for another (arg 1) in one or more files or in th stdin/stdout stream for file name "-" (or if no names given).
#!/usr/bin/env python3
from os import rename,remove
from os.path import exists
from subprocess import run
from sys import argv,stderr,stdin,stdout
from time import time as secs
dne = 0
abort = False
if len(argv)<3:
    exit('string substition needs old string in arg 1 and new string in arg2 followed by an optional list of file names.')
exe = argv.pop(0)
old = argv.pop(0)
new = argv.pop(0)
fns = argv if argv else ['-']
for fn in fns:
    if fns.count(fn)>1:
        exit('duplicate file name: '+repr(fn))
    if fn!='-':
        if not exists(fn):
            print('file does not exist: '+repr(fn),file=stderr)
            dne += 1
if dne:
    exit('aborting due to '+str(dne)+' missing file'+'s'[dne==1:])
for fn in fns:
    if fn=='-':
        tn = None
        fi,fo = stdin,stdout
    else:
        tn = fn+'+'+str(int(secs()*3906250))
        fi = open(fn,'r')
        fo = open(tn,'w')
    changed = 0
    for ol in fi:
        nl = ol.replace(old,new)
        if nl!=ol:
            changed += 1
        fo.write(nl)
    fi.close()
    fo.close()
    if changed and fn!='-':
        run(['chmod','--quiet','--reference='+fn,tn])
        run(['chown','--quiet','--reference='+fn,tn])
        rename(fn,fn+'~')
        rename(tn,fn)
    else:
        if tn:
            remove(tn)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Messages In This Thread
sub command - by Skaperen - Mar-07-2020, 07:26 PM
RE: sub command - by Gribouillis - Mar-07-2020, 11:16 PM
RE: sub command - by Skaperen - Mar-08-2020, 01:32 AM
RE: sub command - by Gribouillis - Mar-08-2020, 05:41 AM
RE: sub command - by buran - Mar-08-2020, 07:20 AM
RE: sub command - by Gribouillis - Mar-08-2020, 09:48 AM
RE: sub command - by ndc85430 - Mar-08-2020, 11:01 AM
RE: sub command - by Skaperen - Mar-08-2020, 10:04 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020