Python脚本的relocatable shebang
Date: 2020/02/04 Tags: Python
下面的脚本将miniconda或类似环境中的python脚本的shebang替换为relocatable, 用于远程执行,比如yarn环境
from pathlib import Path
import sh
root = Path('/data/andyfei/o/bin/')
x = sh.file(Path('/data/andyfei/o/bin/dask-yarn'))
def is_pyfile(p):
return 'Python script' in sh.file(p)
def replace_header(p):
print(f'rewrite {p}')
with open(p) as f:
lines = list(f)
lines = lines[1:]
lines = [
'#!/bin/bash -e\n',
r'''"eval" '$(cd `dirname $0`; pwd)/python3 $(cd `dirname $0`; pwd)/$(basename $0) "$@" && exit 0' ''' + '\n'
] + lines
with open(p, 'w') as f:
f.write(''.join(lines))
for p in root.iterdir():
if not p.is_file():
continue
if p.is_symlink():
continue
if is_pyfile(p):
replace_header(p)