text
stringlengths
81
112k
Dump each message from kafka topic to stdio. def follow_topic(kafka_class, name, retry_interval=1, **kafka_init): """Dump each message from kafka topic to stdio.""" while True: try: client = kafka_class(**kafka_init) topic = client.topics[name] consumer = topic.get_s...
Dump each line of input to stdio. def follow_fd(fd): """Dump each line of input to stdio.""" dump = Dump() for line in fd: if not line.strip(): continue with flushing(sys.stdout, sys.stderr): status = load(line) if status: dump(status)
Determine if the error means to retry or fail, True to retry. def should_try_kafka_again(error): """Determine if the error means to retry or fail, True to retry.""" msg = 'Unable to retrieve' return isinstance(error, KafkaException) and str(error).startswith(msg)
Check if a file is valid Glove format. Args: line0 (bytes): First line of the file line1 (bytes): Second line of the file Returns: boo: ``True`` if it is valid. ``False`` if it is invalid. def check_valid(line0, line1): """ Check if a file is valid Glove format. Args: ...
Load word embedding file with predefined vocabulary Args: fin (File): File object to read. File should be open for reading ascii. vocab (dict): Mapping from words (``bytes``) to vector indices (``int``). dtype (numpy.dtype): Element data type to use for the array. Returns: ...
Load word embedding file. Args: fin (File): File object to read. File should be open for reading ascii. dtype (numpy.dtype): Element data type to use for the array. max_vocab (int): Number of vocabulary to read. Returns: numpy.ndarray: Word embedding representation vectors ...
Updates python dependencies def python_dependencies(context: Context, extras=None): """ Updates python dependencies """ with mock.patch('setuptools.setup'): from setup import install_requires, extras_require requirements = install_requires.copy() if extras: requirem...
Updates the version of MTP-common def set_version(context: Context, version=None, bump=False): """ Updates the version of MTP-common """ if bump and version: raise TaskError('You cannot bump and set a specific version') if bump: from mtp_common import VERSION version = list...
Generates static documentation def docs(context: Context): """ Generates static documentation """ try: from sphinx.application import Sphinx except ImportError: context.pip_command('install', 'Sphinx') from sphinx.application import Sphinx context.shell('cp', 'README.rs...
Deletes build outputs def clean(context: Context, delete_dependencies: bool = False): """ Deletes build outputs """ paths = ['docs/build', 'build', 'dist', '.eggs'] + glob.glob('*.egg-info') context.shell('rm -rf %s' % paths_for_shell(paths)) context.shell('find %s -name "*.pyc" -or -name __pyc...
Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong. def authenticate(self, username=None, password=None): """ Returns a valid `MojUser` if the authentication is successful or None if the credentials were wrong. """ data = ...
Requests and stores the NOMIS API client token from mtp-api def get_client_token(): """ Requests and stores the NOMIS API client token from mtp-api """ if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''): return settings.NOMIS_API_CLIENT_TOKEN global client_token if not client_token or c...
Return a new QuerySet instance that will include related objects. If fields are specified, they must be non-hidden relationships. If select_related(None) is called, clear the list. def include(self, *fields, **kwargs): """ Return a new QuerySet instance that will include related objec...
Search for DICOM files within a given directory and receive back a dictionary of {StudyInstanceUID: {SeriesNumber: [files]}} Example usage:: >>> import yaxil.dicom >>> yaxil.dicom.search("~/dicoms").keys() ['1.2.340.500067.8.9.10.11012.13000001401516017181900000200'] :...
Replace Django's generic error messages with MTP-specific versions NB: avoid trailing full stops visually, they are added for screen readers in templates def replace_default_error_messages(): """ Replace Django's generic error messages with MTP-specific versions NB: avoid trailing full stops visually, ...
Load vocabulary from vocab file created by word2vec with ``-save-vocab <file>`` option. Args: fin (File): File-like object to read from. encoding (bytes): Encoding of the input file as defined in ``codecs`` module of Python standard library. errors (bytes): Set the error han...
Returns: a dict with: pk: the pk of the user token: dict containing all the data from the api (access_token, refresh_token, expires_at etc.) user_data: dict containing user data such as first_name, last_name etc. if the authentication s...
Instructs the API to delete this access token and associated refresh token def revoke_token(access_token): """ Instructs the API to delete this access token and associated refresh token """ response = requests.post( get_revoke_token_url(), data={ 'token': access_token, ...
:return: an authenticated api session def get_authenticated_api_session(username, password): """ :return: an authenticated api session """ session = MoJOAuth2Session( client=LegacyApplicationClient( client_id=settings.API_CLIENT_ID ) ) session.fetch_token( t...
Memoization wrapper that can handle function attributes, mutable arguments, and can be applied either as a decorator or at runtime. :param fn: Function :type fn: function :returns: Memoized function :rtype: function def lru_cache(fn): ''' Memoization wrapper that can handle function attri...
Check :func:`word_embedding_loader.loader.glove.check_valid` for the API. def check_valid(line0, line1): """ Check :func:`word_embedding_loader.loader.glove.check_valid` for the API. """ data0 = line0.split(b' ') if len(data0) != 2: return False # check if data0 is int values try: ...
Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API. def load_with_vocab(fin, vocab, dtype=np.float32): """ Refer to :func:`word_embedding_loader.loader.glove.load_with_vocab` for the API. """ line = next(fin) data = line.strip().split(b' ') assert len(data) == 2 ...
Refer to :func:`word_embedding_loader.loader.glove.load` for the API. def load(fin, dtype=np.float32, max_vocab=None): """ Refer to :func:`word_embedding_loader.loader.glove.load` for the API. """ vocab = {} line = next(fin) data = line.strip().split(b' ') assert len(data) == 2 words = ...
Read connection details from an xnat_auth XML file Example: >>> import yaxil >>> auth = yaxil.auth('xnatastic') >>> auth.url, auth.username, auth.password ('https://www.xnatastic.org/', 'username', '********') :param alias: XNAT alias :type alias: str :param url: XNAT U...
Retrieve Subject tuples for subjects returned by this function. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.subjects(auth, 'AB1234C') Subject(uri=u'/data/experiments/XNAT_S0001', label=u'AB1234C', id=u'XNAT_S0001', ...
Retrieve Experiment tuples for experiments returned by this function. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.experiment(auth, 'AB1234C') Experiment(uri=u'/data/experiments/XNAT_E0001', label=u'AB1234C', id=u'XNAT_...
Get the Accession ID for any Experiment label. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.accession(auth, 'AB1234C') u'XNAT_E00001' :param auth: XNAT authentication :type auth: :mod:`yaxil.XnatAuth` :param la...
Download scan data from XNAT. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.download(auth, 'AB1234C', ['1', '2'], out_dir='./data') :param auth: XNAT authentication object :type auth: :mod:`yaxil.XnatAuth` :param la...
Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zipfile.ZipFile :param out_dir: Output directory :type out_dir: str def extract(zf, content, out_dir='.'): ''' Extracting a Java 1.6 XNAT ZIP archive in Python. :param zf: ZipFile object :type zf: zi...
Quick validation of JSON result set returned by XNAT. :param r: Result set data in JSON format :type r: dict :param check: Fields to check :type check: tuple :returns: Result set is valid :rtype: bool def __quick_validate(r, check=('ResultSet', 'Result', 'totalRecords')): ''' Quick val...
Search for scans by supplying a set of SQL-based conditionals. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> query = { ... 'eor1': "note LIKE %EOR1%", ... 'eor2': "note LIKE %EOR2%", ... 'mpr': "series_descr...
Get scan information for a MR Session as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for scan in yaxil.scans2(auth, 'AB1234C'): ... print(json.dumps(scan, indent=2)) :...
Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedboldqc2(auth, 'AB1234C') ... print(json.dumps(eqc, indent=2)) :param au...
Issue a GET request to the XNAT REST API and box the response content. Example: >>> import yaxil >>> from yaxil import Format >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.get(auth, '/data/experiments', Format.JSON) :param auth: XNAT authent...
Autobox response content. :param content: Response content :type content: str :param format: Format to return :type format: `yaxil.Format` :returns: Autoboxed content :rtype: dict|xml.etree.ElementTree.Element|csvreader def _autobox(content, format): ''' Autobox response content. ...
Test if a project contains any items of a particular xsi:type. Example: >>> import yaxil >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> yaxil.has(auth, 'neuroinfo:extendedboldqc', project='MyProject') :param auth: XNAT authentication :type auth: :mod:`yaxi...
Returns a cached copy of the user if it exists or calls `auth_get_user` otherwise. def get_user(request): """ Returns a cached copy of the user if it exists or calls `auth_get_user` otherwise. """ if not hasattr(request, '_cached_user'): request._cached_user = auth_get_user(request) ...
Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. def ensure_compatible_admin(view): """ Ensures that the user is in exactly one role. Other checks could be added, such as requiring one prison if in prison-clerk role. ""...
Method decorator to catch and log errors, then send fail message. def fault_barrier(fn): """Method decorator to catch and log errors, then send fail message.""" @functools.wraps(fn) def process(self, tup): try: return fn(self, tup) except Exception as e: if isinstanc...
Initialization steps: 1. Get :func:`~birding.search.search_manager_from_config`. 2. Prepare to track searched terms as to avoid redundant searches. def initialize(self, conf, ctx): """Initialization steps: 1. Get :func:`~birding.search.search_manager_from_config`. 2. Prepare t...
Process steps: 1. Stream in (term, timestamp). 2. Perform :meth:`~birding.search.SearchManager.search` on term. 3. Emit (term, timestamp, search_result). def process(self, tup): """Process steps: 1. Stream in (term, timestamp). 2. Perform :meth:`~birding.search.SearchM...
Process steps: 1. Stream in (term, timestamp, search_result). 2. Perform :meth:`~birding.search.SearchManager.lookup_search_result`. 3. Emit (term, timestamp, lookup_result). def process(self, tup): """Process steps: 1. Stream in (term, timestamp, search_result). 2. Pe...
Initialization steps: 1. Prepare elasticsearch connection, including details for indexing. def initialize(self, conf, ctx): """Initialization steps: 1. Prepare elasticsearch connection, including details for indexing. """ config = get_config()['ElasticsearchIndexBolt'] ...
Process steps: 1. Index third positional value from input to elasticsearch. def process(self, tup): """Process steps: 1. Index third positional value from input to elasticsearch. """ self.es.bulk( self.generate_bulk_body(tup.values[2]), index=self.index...
Initialization steps: 1. Connect to Kafka. 2. Prepare Kafka producer for `tweet` topic. 3. Prepare to track tweets published to topic, to avoid redundant data. def initialize(self, conf, ctx): """Initialization steps: 1. Connect to Kafka. 2. Prepare Kafka producer for ...
Process steps: 1. Stream third positional value from input into Kafka topic. def process(self, tup): """Process steps: 1. Stream third positional value from input into Kafka topic. """ status_seq = self.iter_using_shelf(tup.values[2], self.tweet_shelf) # This could be ...
Get a `SearchManager` instance dynamically based on config. `config` is a dictionary containing ``class`` and ``init`` keys as defined in :mod:`birding.config`. def search_manager_from_config(config, **default_init): """Get a `SearchManager` instance dynamically based on config. `config` is a diction...
Create a BIDS output directory from configuration file def bids_from_config(sess, scans_metadata, config, out_base): ''' Create a BIDS output directory from configuration file ''' # get session and subject labels from scan metadata _item = next(iter(scans_metadata)) session,subject = _item['ses...
Download anatomical data and convert to BIDS def proc_anat(config, args): ''' Download anatomical data and convert to BIDS ''' refs = dict() for scan in iterconfig(config, 'anat'): ref = scan.get('id', None) templ = 'sub-${sub}_ses-${ses}' if 'acquisition' in scan: ...
Iterate over BIDS configuration file def iterconfig(config, scan_type): ''' Iterate over BIDS configuration file ''' if scan_type in config: for modality,scans in iter(config[scan_type].items()): for scan in scans: scan.update({ 'type': scan_type,...
Rename magnitude fieldmap file to BIDS specification def rename_fmapm(bids_base, basename): ''' Rename magnitude fieldmap file to BIDS specification ''' files = dict() for ext in ['nii.gz', 'json']: for echo in [1, 2]: fname = '{0}_e{1}.{2}'.format(basename, echo, ext) ...
Run dcm2niix on input file def convert(input, output): ''' Run dcm2niix on input file ''' dirname = os.path.dirname(output) if not os.path.exists(dirname): os.makedirs(dirname) basename = os.path.basename(output) basename = re.sub('.nii(.gz)?', '', basename) dcm2niix = commons.w...
Adds messages for each error returned from the MTP apis Useful for displaying errors when there's no form on the page :param request: HttpRequest :param error: HttpClientError :param fallback_text: fallback error text def api_errors_to_messages(request, error, fallback_text): """ Adds messages ...
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator, this method loads all pages into a single results list :param api_endpoint: slumber callable, e.g. `[api_client].cashbook.transactions.locked.get` :param kwargs: additional arguments to pass into api callable def ret...
Some MTP apis are paginated using Django Rest Framework's LimitOffsetPagination paginator, this method loads all pages into a single results list :param session: Requests Session object :param path: URL path :param params: additional URL params def retrieve_all_pages_for_path(session, path, **params): ...
Factory to dispatch spout class based on config. def DispatchSpout(*a, **kw): """Factory to dispatch spout class based on config.""" spout_class_name = get_config()['Spout'] spout_class = import_name(spout_class_name, default_ns='birding.spout') return spout_class(*a, **kw)
Initialization steps: 1. Prepare sequence of terms based on config: TermCycleSpout/terms. def initialize(self, stormconf, context): """Initialization steps: 1. Prepare sequence of terms based on config: TermCycleSpout/terms. """ self.terms = get_config()['TermCycleSpout']['ter...
Next tuple steps: 1. Emit (term, timestamp) for next term in sequence w/current UTC time. def next_tuple(self): """Next tuple steps: 1. Emit (term, timestamp) for next term in sequence w/current UTC time. """ term = next(self.term_seq) timestamp = datetime.datetime.utc...
Cast a basestring to a more appropriate type. Example:: >>> from yaxil import cast >>> type(cast("999")) <type 'int'> :param s: String :type s: basestring :returns: Casted string :rtype: int|float|str def cast(s): ''' Cast a basestring to a more appropriate type...
Write a file atomically by writing the file content to a temporary location first, then renaming the file. TODO: this relies pretty heavily on os.rename to ensure atomicity, but os.rename does not silently overwrite files that already exist on Windows natively. For now, the functionality provide...
Same as which command on Linux def which(x): ''' Same as which command on Linux ''' for p in os.environ.get('PATH').split(os.pathsep): p = os.path.join(p, x) if os.path.exists(p): return os.path.abspath(p) return None
Starts a development server with auto-building and live-reload def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030): """ Starts a development server with auto-building and live-reload """ try: from watchdog.observers import Observer except ImportError: ...
Creates directories needed for build outputs def create_build_paths(context: Context): """ Creates directories needed for build outputs """ paths = [context.app.asset_build_path, context.app.screenshots_build_path, context.app.collected_assets_path] for path in filter(None, paths): os.maked...
Updates python dependencies def python_dependencies(context: Context, common_path=None): """ Updates python dependencies """ context.pip_command('install', '-r', context.requirements_file) if common_path: context.pip_command('uninstall', '--yes', 'money-to-prisoners-common') context...
Updates node.js dependencies def node_dependencies(context: Context): """ Updates node.js dependencies """ args = ['--loglevel', {0: 'silent', 1: 'warn', 2: 'info'}[context.verbosity]] if not context.use_colour: args.append('--color false') args.append('install') return context.shel...
Runs the app in a docker container; for local development only! Once performed, `docker-compose up` can be used directly def local_docker(context: Context): """ Runs the app in a docker container; for local development only! Once performed, `docker-compose up` can be used directly """ output = ...
Compiles javascript def bundle_javascript(context: Context): """ Compiles javascript """ args = ['--bail'] if context.verbosity > 0: args.append('--verbose') if not context.use_colour: args.append('--no-colors') return context.node_tool('webpack', *args)
Compiles stylesheets def bundle_stylesheets(context: Context): """ Compiles stylesheets """ args = [ '--output', context.app.scss_build_path, '--output-style', 'compressed', ] if context.verbosity == 0: args.append('--quiet') if not context.use_colour: args.a...
Tests javascript for code and style errors def lint_javascript(context: Context): """ Tests javascript for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'eslintrc.json'), '--format', 'stylish', ] if co...
Tests stylesheets for code and style errors def lint_stylesheets(context: Context): """ Tests stylesheets for code and style errors """ args = [ '--config', os.path.join(context.app.common_templates_path, 'mtp_common', 'build_tasks', 'sass-lint.yml'), '--format', 'stylish', '--s...
Installs GOV.UK template def govuk_template(context: Context, version='0.23.0', replace_fonts=True): """ Installs GOV.UK template """ if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')): # NB: check is only on main template and not the assets included return url ...
Collects assets from GOV.UK frontend toolkit def additional_assets(context: Context): """ Collects assets from GOV.UK frontend toolkit """ rsync_flags = '-avz' if context.verbosity == 2 else '-az' for path in context.app.additional_asset_paths: context.shell('rsync %s %s %s/' % (rsync_flags...
Pre-compiles python modules def precompile_python_code(context: Context): """ Pre-compiles python modules """ from compileall import compile_dir kwargs = {} if context.verbosity < 2: kwargs['quiet'] = True compile_dir(context.app.django_app_name, **kwargs)
Collects text into translation source files def make_messages(context: Context, javascript=False, fuzzy=False): """ Collects text into translation source files """ kwargs = { 'all': True, 'keep_pot': True, 'no_wrap': True, } if fuzzy: kwargs['allow_fuzzy'] = True...
Synchronises translations with transifex.com def translations(context: Context, pull=False, push=False): """ Synchronises translations with transifex.com """ if not (pull or push): raise TaskError('Specify whether to push or pull translations') if pull: context.shell('tx', 'pull') ...
Deletes build outputs def clean(context: Context, delete_dependencies: bool = False): """ Deletes build outputs """ paths = [context.app.asset_build_path, context.app.collected_assets_path, context.app.govuk_templates_path, 'docker-compose.yml', 'package.json', 'package-lock.json', 'webpac...
CSRF-failure view which converts the failed POST request into a GET and calls the original view with a sensible error message presented to the user. :param request: the HttpRequest :param reason: non-localised failure description def csrf_failure(request, reason=''): """ CSRF-failure view which...
Computes the positions of the elctrodes based on the elinfo Parameters ---------- elinfo: dict Contains electrode information from yaml file (dim, pitch, sortlist, plane, pos) Returns ------- positions: np.array 3d points with the centers of the electrodes def get_positions(el...
Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns ------- def add_mea(mea_yaml_path): '''Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns ------- ...
Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns ------- def remove_mea(mea_name): '''Adds the mea design defined by the yaml file in the install folder Parameters ---------- mea_yaml_file Returns ------- ...
Get the first and second lines Args: f (filelike): File that is opened for ascii. Returns: bytes def _get_two_lines(f): """ Get the first and second lines Args: f (filelike): File that is opened for ascii. Returns: bytes """ l0 = f.readline() l1 = ...
Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class def classify_format(f): """ Determine the format of word embedding file by their conte...
Load pretrained word embedding from a file. Args: path (str): Path of file to load. vocab (str or None): Path to vocabulary file created by word2vec with ``-save-vocab <file>`` option. If vocab is given, :py:attr:`~vectors` and :py:attr:`~vocab` is ordere...
Save object as word embedding file. For most arguments, you should refer to :func:`~word_embedding_loader.word_embedding.WordEmbedding.load`. Args: use_load_condition (bool): If `True`, options from :func:`~word_embedding_loader.word_embedding.WordEmbedding.load` ...
Converts a list of paths for use in shell commands def paths_for_shell(paths, separator=' '): """ Converts a list of paths for use in shell commands """ paths = filter(None, paths) paths = map(shlex.quote, paths) if separator is None: return paths return separator.join(paths)
Decorates a callable to turn it into a task def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False): """ Decorates a callable to turn it into a task """ def outer(func): task = Task(func, *dependencies, default=default, hidden=hidden, ignore...
Looks up a task by name or by callable def lookup_task(self, task): """ Looks up a task by name or by callable """ if isinstance(task, str): try: return self[task] except KeyError: pass raise TaskError('Unknown task %s' % t...
Returns the default task if there is only one def get_default_task(self): """ Returns the default task if there is only one """ default_tasks = list(filter(lambda task: task.default, self.values())) if len(default_tasks) == 1: return default_tasks[0]
Reads a function or method signature to produce a set of parameters def from_callable(cls, func, ignored_parameters=set()): """ Reads a function or method signature to produce a set of parameters """ group = cls() signature = inspect.signature(func) for parameter in sign...
Produces a set of parameters from a mapping def from_mapping(cls, mapping): """ Produces a set of parameters from a mapping """ group = cls() for name, value in mapping.items(): if name.startswith('_'): continue group[name] = Parameter( ...
Converts the set of parameters into a dict def to_dict(self): """ Converts the set of parameters into a dict """ return dict((parameter.name, parameter.value) for parameter in self.values())
Takes arguments from a list while there are parameters that can accept them def consume_arguments(self, argument_list): """ Takes arguments from a list while there are parameters that can accept them """ while True: argument_count = len(argument_list) for paramet...
Updates the set of parameters from a mapping for keys that already exist def update_from(self, mapping): """ Updates the set of parameters from a mapping for keys that already exist """ for key, value in mapping.items(): if key in self: if isinstance(value, P...
Produces a parameter from a function or method def from_callable_parameter(cls, parameter): """ Produces a parameter from a function or method """ if parameter.kind == parameter.KEYWORD_ONLY or \ parameter.kind == parameter.POSITIONAL_OR_KEYWORD and parameter.default is ...
Returns the constraint callable given a value def constraint_from_type(cls, value): """ Returns the constraint callable given a value """ if value is None: return None value_type = type(value) if value_type in (str, int, bool): return value_type ...
Returns a constraint callable based on choices of a given type def constraint_from_choices(cls, value_type: type, choices: collections.Sequence): """ Returns a constraint callable based on choices of a given type """ choices_str = ', '.join(map(str, choices)) def constraint(val...
Returns the name of the parameter as a command line flag def arg_name(self): """ Returns the name of the parameter as a command line flag """ if self.constraint is bool and self.value: return '--no-%s' % self.name.replace('_', '-') return '--%s' % self.name.replace('...
Takes arguments from a list while this parameter can accept them def consume_arguments(self, argument_list): """ Takes arguments from a list while this parameter can accept them """ if len(argument_list) == 0: return [] if argument_list[0] == self.arg_name: ...
Runs a pip command def pip_command(self, command, *args): """ Runs a pip command """ try: from pip._internal import main as pip_main except ImportError: from pip import main as pip_main args = [command] + list(args) if self.verbosity == 0...
Runs a shell command def shell(self, command, *args, environment=None): """ Runs a shell command """ command += ' ' + ' '.join(args) command = command.strip() self.debug(self.yellow_style('$ %s' % command)) env = self.env.copy() env.update(environment or ...