Skip to content

Latest commit

 

History

History
64 lines (40 loc) · 1.46 KB

File metadata and controls

64 lines (40 loc) · 1.46 KB

Python Skills and Tricks

Python module

Check if a program exists from a python script

from https://stackoverflow.com/questions/11210104/check-if-a-program-exists-from-a-python-script

  • shutil.which
def is_tool(name):
    """Check whether `name` is on PATH and marked as executable."""

    # from whichcraft import which in python2.x
    from shutil import which

    return which(name) is not None
  • distutils.spawn.find_executable
def is_tool(name):
    """Check whether `name` is on PATH."""

    from distutils.spawn import find_executable

    return find_executable(name) is not None

Write strings to gzip file

from https://stackoverflow.com/questions/49286135/write-strings-to-gzip-file

# opt1: encode string
with gzip.open('file.gz', 'wb') as f:
    f.write('Hello world!'.encode())

# opt2: write strings to your file when you open it in the wt mode
with gzip.open('file.gz', 'wt') as f:
    f.write('Hello world!')

Python Package

Access Data in Package Subdirectory

from https://stackoverflow.com/questions/5897666/how-do-i-use-data-in-package-data-from-source-code

import pkg_resources

DATA_PATH = pkg_resources.resource_filename('<package name>', 'data')
DB_FILE = pkg_resources.resource_filename('<package name>', 'data/sqlite.db')

[返回首页]