Last active
June 17, 2019 03:43
-
-
Save nnnewb/f06f5859f55ad9dc1b89312e31242ce5 to your computer and use it in GitHub Desktop.
制作命令行工具的实用函数集
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import subprocess | |
import logging | |
# ! 工具函数 | |
# ---------------------------------------------------------------------------- | |
def require(package, import_name=None, editable=False, quiet=True, index='https://pypi.org/simple'): | |
logger = logging.getLogger('require') | |
try: | |
from pip import main | |
except ImportError: | |
try: | |
from pip._internal import main | |
except ImportError: | |
logger.error('请先安装 pip 才能继续。') | |
pip = main | |
install_options = [opt for opt in filter(bool, [ | |
'-e' if editable else None, | |
'-q' if quiet else None, | |
])] | |
if pip(['show', package, '-q']): # if package does not exists | |
if pip(['install', package, '-i', index, *install_options]): # if install package failed | |
logger.error('无法安装依赖包 {}'.format(package)) | |
return __import__(import_name if import_name else package) | |
def run(cmd, cwd=None, silence=False, capture=None, fatal=False): | |
script_logger = logging.getLogger('run') | |
script_logger.info('>>> {}'.format(cmd)) | |
proc = subprocess.Popen(['sh', '-c', cmd], executable='sh', stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) | |
o, e = proc.communicate() | |
if sys.version_info.major > 2: | |
o = o.decode() | |
e = e.decode() | |
if proc.returncode != 0: | |
if not silence: | |
script_logger.error('错误:\n' + '命令:{}\n'.format(cmd) + 'stdout:\n\n{}\n'.format(o) + | |
'stderr:\n\n{}\n'.format(e)) | |
if fatal: | |
script_logger.error('发生了致命错误,程序即将退出。') | |
exit(-1) | |
return proc.returncode | |
if capture == 'stdout': | |
return o | |
elif capture == 'stderr': | |
return e | |
return proc.returncode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment