#! /usr/libexec/platform-python
# Change the #! line (shebang) occurring in Python scripts. The new interpreter
# pathname must be given with a -i option.
# Command line arguments are files or directories to be processed.
# Directories are searched recursively for files whose name looks
# Symbolic links are always ignored (except as explicit directory
# The original file is kept as a back-up (with a "~" attached to its name),
# -n flag can be used to disable this.
# Sometimes you may find shebangs with flags such as `#! /usr/bin/env python -si`.
# Normally, pathfix overwrites the entire line, including the flags.
# To change interpreter and keep flags from the original shebang line, use -k.
# If you want to keep flags and add to them one single literal flag, use option -a.
# Undoubtedly you can do this using find and sed or perl, but this is
# a nice example of Python code that recurses down a directory tree
# and uses regular expressions. Also note several subtleties like
# preserving the file's mode and avoiding to even write a temp file
# when no changes are needed for a file.
# NB: by changing only the function fixfile() you can turn this
# into a program for a different change to Python programs...
preserve_timestamps = False
global preserve_timestamps
usage = ('usage: %s -i /interpreter -p -n -k -a file-or-directory ...\n' %
opts, args = getopt.getopt(sys.argv[1:], 'i:a:kpn')
except getopt.error as msg:
new_interpreter = a.encode()
preserve_timestamps = True
err("-a option doesn't support whitespaces")
if not new_interpreter or not new_interpreter.startswith(b'/') or \
err('-i option or file-or-directory missing\n')
if recursedown(arg): bad = 1
elif os.path.islink(arg):
err(arg + ': will not process symbolic links\n')
ispythonprog = re.compile(r'^[a-zA-Z0-9_]+\.py$')
return bool(ispythonprog.match(name))
def recursedown(dirname):
dbg('recursedown(%r)\n' % (dirname,))
names = os.listdir(dirname)
err('%s: cannot list directory: %r\n' % (dirname, msg))
if name in (os.curdir, os.pardir): continue
fullname = os.path.join(dirname, name)
if os.path.islink(fullname): pass
elif os.path.isdir(fullname):
if fix(fullname): bad = 1
if recursedown(fullname): bad = 1
## dbg('fix(%r)\n' % (filename,))
err('%s: cannot open: %r\n' % (filename, msg))
rep(filename+': no change\n')
head, tail = os.path.split(filename)
tempname = os.path.join(head, '@' + tail)
err('%s: cannot create: %r\n' % (tempname, msg))
rep(filename + ': updating\n')
# Finishing touch -- move files
# First copy the file's mode to the temp file
statbuf = os.stat(filename)
os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
# Then make a backup of the original file as filename~
os.rename(filename, filename + '~')
err('%s: warning: backup failed (%r)\n' % (filename, msg))
err('%s: warning: removing failed (%r)\n' % (filename, msg))
# Now move the temp file to the original file
os.rename(tempname, filename)
err('%s: rename failed (%r)\n' % (filename, msg))
os.utime(filename, (atime, mtime))
err('%s: reset of timestamp failed (%r)\n' % (filename, msg))
def parse_shebang(shebangline):
shebangline = shebangline.rstrip(b'\n')
start = shebangline.find(b' -')
return shebangline[start:]
def populate_flags(shebangline):
old_flags = parse_shebang(shebangline)
old_flags = old_flags[2:]
if not (old_flags or add_flags):
# On Linux, the entire string following the interpreter name
# is passed as a single argument to the interpreter.
# e.g. "#! /usr/bin/python3 -W Error -s" runs "/usr/bin/python3 "-W Error -s"
# so shebang should have single '-' where flags are given and
# flag might need argument for that reasons adding new flags is
# between '-' and original flags
# e.g. #! /usr/bin/python3 -sW Error
return b' -' + add_flags + old_flags
if not line.startswith(b'#!'):
if b"python" not in line:
flags = populate_flags(line)
return b'#! ' + new_interpreter + flags + b'\n'
if __name__ == '__main__':