with open('my_script.sh', 'w') as fd:
    fd.write('#!/bin/sh\n')
fd.write('echo $PATH\n')
mode = os.fstat(fd.fileno()).st_mode
mode |= stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
os.fchmod(fd.fileno(), stat.S_IMODE(mode))
Set execute bit for a file using python