Gist Shell

Iridescent

ColorLESS

Author: lilydjwg

来自: https://github.com/lilydjwg/winterpy/

#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
import sys
import argparse
import subprocess
from pygments import highlight
import pygments.util
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter
from pygments.lexers import guess_lexer, guess_lexer_for_filename
def main(fname, lang):
if fname == '-':
code = sys.stdin.read()
else:
code = open(fname).read()
if lang:
lexer = get_lexer_by_name(lang)
else:
try:
lexer = guess_lexer_for_filename(fname, code)
except pygments.util.ClassNotFound:
lexer = guess_lexer(code)
if sys.stdout.isatty():
p = subprocess.Popen(['less', '-RFX'], stdin=subprocess.PIPE,
universal_newlines=True)
output = p.stdin
else:
p = None
output = sys.stdout
print(highlight(code, lexer, TerminalFormatter()), file=output)
output.close()
if p:
p.wait()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='用 less 显示高亮的代码')
parser.add_argument('files', metavar='FILE', nargs='*',
help='要高亮的文件')
parser.add_argument('-l', '--lang', dest='lang', default=None,
help='语法类型')
args = parser.parse_args()
if args.files:
for l in args.files:
main(l, args.lang)
else:
main('-', args.lang)
view raw colorless hosted with ❤ by GitHub

PyPacker

Author: lilydjwg

将一个 Python 程序所 import 的所有用户自己的模块找出来一起打包

#!/usr/bin/env python3
# coding=utf-8
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
'''
将一个 Python 程序所 import 的所有用户自己的模块找出来一起打包
'''
import sys, os
import tarfile
from python import mymodsImported
def getModuleFiles(file):
return {m.__file__ for m in mymodsImported(file)}
if __name__ == '__main__':
fin = dry_run = False
if len(sys.argv) == 2:
fin = sys.argv[1]
elif len(sys.argv) == 3 and sys.argv[1] in ('-l', '--list', '--dry-run'):
dry_run = True
fin = sys.argv[2]
else:
print('用法:', os.path.basename(sys.argv[0]), '[选项] 要打包的 Python 程序文件')
print("\t选项 '-l', '--list' 或 '--dry-run' 指定不执行打包,只列出要打包的文件")
sys.exit(2)
if fin:
files = getModuleFiles(fin)
files.add(fin)
if dry_run:
print('\n'.join(files))
else:
archieve = os.path.basename(fin)
with tarfile.open(archieve + '.tar.bz2', 'w:bz2') as f:
for i in files:
f.add(i, os.path.split(i)[1])
print('完成!')
view raw pypacker.py hosted with ❤ by GitHub

#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
import os
def mymodsImported(scriptfile):
'''导入的模块哪些是通过环境变量找到的?'''
try:
dirs = os.getenv('PYTHONPATH').split(':')
except AttributeError:
return []
if not dirs:
return []
from modulefinder import ModuleFinder
finder = ModuleFinder()
finder.run_script(scriptfile)
def filterdir(mod):
file = mod.__file__
if not file:
return False
for i in dirs:
if file.startswith(i):
return True
return False
return [m for m in finder.modules.values() if filterdir(m)]
view raw python.py hosted with ❤ by GitHub

saveList

Author: lilydjwg

#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
# This is free software: you are free to change and redistribute it.
# There is NO WARRANTY, to the extent permitted by law.
'''
类似 git 那样保留一份文件/目录列表
'''
import os
from pickleddata import PData
from path import path
from termcolor import colored as c, cprint
from utils import getchar
datafile = path('~/scripts/python/pydata/dirsave').expand()
dirprompt = '%s 是目录。%s' % (c('%s', 'green', attrs=['bold']), c('加入/忽略/进入/列出文件/tree/Vim/跳过?(y/n/e/l/t/v/s) ', 'blue'))
fileprompt = '%s %s' % (c('%s', 'green', attrs=['bold']), c('加入/忽略/Vim/跳过?(y/n/v/s) ', 'blue'))
def dirsave(startdir, data):
for f in startdir.list():
key = f.basename
if key.endswith('~'):
continue
ans = ''
if isinstance(data.get(key), bool):
continue
elif isinstance(data.get(key), dict):
dirsave(f, data[key])
continue
if f.isdir():
while not ans:
ans = getchar(dirprompt % f.value)
if ans == 'y':
data[key] = True
elif ans == 'n':
data[key] = False
elif ans == 'e':
data[key] = {}
dirsave(f, data[key])
elif ans == 'l':
os.chdir(f.value)
os.system('ls --color=auto')
ans = ''
elif ans == 't':
os.chdir(f.value)
os.system('tree -C')
ans = ''
elif ans == 'v':
os.chdir(f.value)
os.system("vim '%s'" % key)
ans = ''
elif ans == 's':
continue
else:
cprint('无效的选择。', 'red')
ans = ''
else:
while not ans:
ans = getchar(fileprompt % f.value)
if ans == 'y':
data[key] = True
elif ans == 'n':
data[key] = False
elif ans == 'v':
os.system("vim '%s'" % f.value)
ans = ''
elif ans == 's':
continue
else:
cprint('无效的选择。', 'red')
ans = ''
if __name__ == '__main__':
with PData(datafile.value, default={}) as d:
dirsave(path('~').expand(), d)
view raw saveList.py hosted with ❤ by GitHub

继续阅读