Python os.getenv() Examples

The following are 30 code examples for showing how to use os.getenv(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os , or try the search function .

Example 1
Project: incubator-spot   Author: apache   File: kerberos.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self):

        self._logger = Util.get_logger('SPOT.COMMON.KERBEROS')
        principal, keytab, sasl_mech, security_proto = config.kerberos()

        if os.getenv('KINITPATH'):
            self._kinit = os.getenv('KINITPATH')
        else:
            self._kinit = "kinit"

        self._kinitopts = os.getenv('KINITOPTS')
        self._keytab = "-kt {0}".format(keytab)
        self._krb_user = principal

        if self._kinit == None or self._keytab == None or self._krb_user == None:
            self._logger.error("Please verify kerberos configuration, some environment variables are missing.")
            sys.exit(1)

        if self._kinitopts is None:
            self._kinit_cmd = "{0} {1} {2}".format(self._kinit, self._keytab, self._krb_user)
        else:
            self._kinit_cmd = "{0} {1} {2} {3}".format(self._kinit, self._kinitopts, self._keytab, self._krb_user) 
Example 2
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    License: MIT License 6 votes vote down vote up
def get_emsdk_root():
    # Shamelessly copied from Godot's detect.py
    em_config_file = os.getenv('EM_CONFIG') or os.path.expanduser('~/.emscripten')
    if not os.path.exists(em_config_file):
        raise BuildError("Emscripten configuration file '%s' does not exist" % em_config_file)
    with open(em_config_file) as f:
        em_config = {}
        try:
            # Emscripten configuration file is a Python file with simple assignments.
            exec(f.read(), em_config)
        except StandardError as e:
            raise BuildError("Emscripten configuration file '%s' is invalid:\n%s" % (em_config_file, e))
    if 'BINARYEN_ROOT' in em_config and os.path.isdir(os.path.join(em_config.get('BINARYEN_ROOT'), 'emscripten')):
        # New style, emscripten path as a subfolder of BINARYEN_ROOT
        return os.path.join(em_config.get('BINARYEN_ROOT'), 'emscripten')
    elif 'EMSCRIPTEN_ROOT' in em_config:
        # Old style (but can be there as a result from previous activation, so do last)
        return em_config.get('EMSCRIPTEN_ROOT')
    else:
        raise BuildError("'BINARYEN_ROOT' or 'EMSCRIPTEN_ROOT' missing in Emscripten configuration file '%s'" % em_config_file) 
Example 3
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    License: MIT License 6 votes vote down vote up
def run_trigger(name, bundleid=None, arg=None):
    """Call an Alfred External Trigger.

    .. versionadded:: 1.31

    If ``bundleid`` is not specified, reads the bundle ID of the current
    workflow from Alfred's environment variables.

    Args:
        name (str): Name of External Trigger to call.
        bundleid (str, optional): Bundle ID of workflow trigger belongs to.
        arg (str, optional): Argument to pass to trigger.
    """
    if not bundleid:
        bundleid = os.getenv('alfred_workflow_bundleid')

    if arg:
        arg = 'with argument "{}"'.format(applescriptify(arg))
    else:
        arg = ''

    script = AS_TRIGGER.format(name=name, bundleid=bundleid,
                               arg=arg)

    run_applescript(script) 
Example 4
Project: FRIDA   Author: LCAV   File: mkl_fft.py    License: MIT License 6 votes vote down vote up
def load_libmkl():
    if os.name == 'posix':
        try:
            lib_mkl = os.getenv('LIBMKL')
            return _ctypes.cdll.LoadLibrary(lib_mkl)
        except:
            pass
        try:
            return _ctypes.cdll.LoadLibrary("libmkl_rt.dylib")
        except:
            raise ValueError('MKL Library not found')

    else:
        try:
            return _ctypes.cdll.LoadLibrary("mk2_rt.dll")
        except:
            raise ValueError('MKL Library not found') 
Example 5
Project: mmdetection   Author: open-mmlab   File: setup.py    License: Apache License 2.0 6 votes vote down vote up
def make_cuda_ext(name, module, sources, sources_cuda=[]):

    define_macros = []
    extra_compile_args = {'cxx': []}

    if torch.cuda.is_available() or os.getenv('FORCE_CUDA', '0') == '1':
        define_macros += [('WITH_CUDA', None)]
        extension = CUDAExtension
        extra_compile_args['nvcc'] = [
            '-D__CUDA_NO_HALF_OPERATORS__',
            '-D__CUDA_NO_HALF_CONVERSIONS__',
            '-D__CUDA_NO_HALF2_OPERATORS__',
        ]
        sources += sources_cuda
    else:
        print(f'Compiling {name} without CUDA')
        extension = CppExtension
        # raise EnvironmentError('CUDA is required to compile MMDetection!')

    return extension(
        name=f'{module}.{name}',
        sources=[os.path.join(*module.split('.'), p) for p in sources],
        define_macros=define_macros,
        extra_compile_args=extra_compile_args) 
Example 6
Project: multibootusb   Author: mbusb   File: osdriver.py    License: GNU General Public License v2.0 6 votes vote down vote up
def gpt_device(self, dev_name):
        disk_dev = self.physical_disk(dev_name)
        cmd = ['parted', disk_dev, '-s', 'print']
        with open(os.devnull) as devnull:
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE, stdin=devnull)
            _cmd_out, _err_out = p.communicate()
            p.wait()
        if p.returncode != 0:
            lang = os.getenv('LANG')
            encoding = lang.rsplit('.')[-1] if lang else 'utf-8'
            raise RuntimeError(str(_err_out, encoding))
        subprocess.check_call(['partprobe', disk_dev])
        if b'msdos' in _cmd_out:
            return False
        if b'gpt' in _cmd_out:
            return True
        raise RuntimeError("Disk '%s' is uninitialized and not usable." %
                           disk_dev) 
Example 7
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: model.py    License: Apache License 2.0 6 votes vote down vote up
def _update_params_on_kvstore_nccl(param_arrays, grad_arrays, kvstore, param_names):
    """Perform update of param_arrays from grad_arrays on NCCL kvstore."""
    valid_indices = [index for index, grad_list in
                     enumerate(grad_arrays) if grad_list[0] is not None]
    valid_grad_arrays = [grad_arrays[i] for i in valid_indices]
    valid_param_arrays = [param_arrays[i] for i in valid_indices]
    valid_param_names = [param_names[i] for i in valid_indices]
    size = len(valid_grad_arrays)
    start = 0
    # Use aggregation by default only with NCCL
    default_batch = '16'
    batch = int(os.getenv('MXNET_UPDATE_AGGREGATION_SIZE', default_batch))
    while start < size:
        end = start + batch if start + batch < size else size
        # push gradient, priority is negative index
        kvstore.push(valid_param_names[start:end], valid_grad_arrays[start:end], priority=-start)
        # pull back the weights
        kvstore.pull(valid_param_names[start:end], valid_param_arrays[start:end], priority=-start)
        start = end 
Example 8
Project: OpenFermion-Cirq   Author: quantumlib   File: run_checks.py    License: Apache License 2.0 6 votes vote down vote up
def parse_args():
    args = sys.argv
    verbose = '--verbose' in args
    only = [e.split('--only=')[1]
            for e in args
            if e.startswith('--only=')]
    checks = all_checks.ALL_CHECKS
    if only:
        checks = [e for e in checks if e.command_line_switch() in only]
        if len(checks) != len(only):
            print('Bad --only argument. Allowed values {!r}.'.format(
                      [e.command_line_switch() for e in all_checks.ALL_CHECKS]),
                  file=sys.stderr)
            sys.exit(1)
    checks = topologically_sorted_checks_with_deps(checks)

    positionals = [arg for arg in args if not arg.startswith('-')]
    pull_request_number = None if len(positionals) < 2 else int(positionals[1])
    access_token = None if len(positionals) < 3 else int(positionals[2])
    if access_token is None:
        access_token = os.getenv('CIRQ_GITHUB_ACCESS_TOKEN')
    return pull_request_number, access_token, verbose, checks 
Example 9
Project: lirpg   Author: Hwhitetooth   File: logger.py    License: MIT License 6 votes vote down vote up
def configure(dir=None, format_strs=None):
    if dir is None:
        dir = os.getenv('OPENAI_LOGDIR')
    if dir is None:
        dir = osp.join(tempfile.gettempdir(),
            datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"))
    assert isinstance(dir, str)
    os.makedirs(dir, exist_ok=True)

    if format_strs is None:
        strs = os.getenv('OPENAI_LOG_FORMAT')
        format_strs = strs.split(',') if strs else LOG_OUTPUT_FORMATS
    output_formats = [make_output_format(f, dir) for f in format_strs]

    Logger.CURRENT = Logger(dir=dir, output_formats=output_formats)
    log('Logging to %s'%dir) 
Example 10
Project: lirpg   Author: Hwhitetooth   File: mpi_fork.py    License: MIT License 6 votes vote down vote up
def mpi_fork(n, bind_to_core=False):
    """Re-launches the current script with workers
    Returns "parent" for original parent, "child" for MPI children
    """
    if n<=1: 
        return "child"
    if os.getenv("IN_MPI") is None:
        env = os.environ.copy()
        env.update(
            MKL_NUM_THREADS="1",
            OMP_NUM_THREADS="1",
            IN_MPI="1"
        )
        args = ["mpirun", "-np", str(n)]
        if bind_to_core:
            args += ["-bind-to", "core"]
        args += [sys.executable] + sys.argv
        subprocess.check_call(args, env=env)
        return "parent"
    else:
        return "child" 
Example 11
Project: epr   Author: wustho   File: epr.py    License: MIT License 6 votes vote down vote up
def loadstate():
    global STATE, STATEFILE
    if os.getenv("HOME") is not None:
        STATEFILE = os.path.join(os.getenv("HOME"), ".epr")
        if os.path.isdir(os.path.join(os.getenv("HOME"), ".config")):
            configdir = os.path.join(os.getenv("HOME"), ".config", "epr")
            os.makedirs(configdir, exist_ok=True)
            if os.path.isfile(STATEFILE):
                if os.path.isfile(os.path.join(configdir, "config")):
                    os.remove(os.path.join(configdir, "config"))
                shutil.move(STATEFILE, os.path.join(configdir, "config"))
            STATEFILE = os.path.join(configdir, "config")
    elif os.getenv("USERPROFILE") is not None:
        STATEFILE = os.path.join(os.getenv("USERPROFILE"), ".epr")
    else:
        STATEFILE = os.devnull

    if os.path.exists(STATEFILE):
        with open(STATEFILE, "r") as f:
            STATE = json.load(f) 
Example 12
Project: aws-ops-automator   Author: awslabs   File: issues_topic.py    License: Apache License 2.0 6 votes vote down vote up
def publish(self, level, msg, ext_info):

        sns_arn = os.getenv(ENV_SNS_ISSUE_TOPIC, None)
        if sns_arn is not None:
            message = {
                "log-group": self._loggroup,
                "log-stream": self._logstream,
                "level": level,
                "message": msg
            }
            if ext_info not in [None, {}]:
                for i in ext_info:
                    message[i.lower()] = ext_info[i]

            topic_msg = safe_json({"default": safe_json(message, indent=3), "lambda": message})
            resp = self.sns_client.publish_with_retries(TopicArn=sns_arn,
                                                        Message=topic_msg,
                                                        MessageStructure="json")
            print(resp) 
Example 13
Project: aws-ops-automator   Author: awslabs   File: action_base.py    License: Apache License 2.0 6 votes vote down vote up
def get_action_session(self, account, param_name=None, logger=None):
        self._logger_.debug("Getting action session for account \"{}\", task is \"{}\", parameter is \"{}\"", account,
                            self._task_, param_name)

        try:
            role_name = self.get(param_name, None)
            if role_name is None:
                role_name = self.get(handlers.TASK_ROLE, None)
            if role_name is None:
                if account == os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT):
                    role_name = None
                else:
                    role_name = handlers.default_rolename_for_stack()

            role_arn = handlers.ARN_ROLE_TEMPLATE.format(account, role_name) if role_name is not None else None
            self._logger_.debug("Role arn is \"{}\"", role_arn)

            return services.get_session(role_arn=role_arn, logger=logger)
        except Exception as ex:
            if logger is not None:
                logger.error(handlers.ERR_CREATING_SESSION, ex)
            return None 
Example 14
Project: aws-ops-automator   Author: awslabs   File: task_configuration.py    License: Apache License 2.0 6 votes vote down vote up
def create_task_config_objects(self, config_item):
        # get the class that implements the action and test if there is a static method for creating templates
        action_class = actions.get_action_class(config_item[configuration.CONFIG_ACTION_NAME])
        create_task_objects_method = getattr(action_class, "create_task_config_objects", None)
        # if the method exists then validate the parameters using the business logic for that class
        bucket = os.getenv(configuration.ENV_CONFIG_BUCKET)
        prefix = "{}/{}/{}/".format(configuration.TASKS_OBJECTS, config_item[configuration.CONFIG_ACTION_NAME],
                                    config_item[configuration.CONFIG_TASK_NAME])
        task_name = config_item[configuration.CONFIG_TASK_NAME]
        try:
            if create_task_objects_method is not None:
                cfg = self.get_parameters(config_item)
                objects = create_task_objects_method(cfg)
                if objects is not None:
                    s3 = boto3.client("s3")
                    for t in objects:
                        s3.put_object(Bucket=bucket, Key=prefix + t, Body=objects[t])
                        self._logger.info("Created config object {}/{} in bucket {} for task {}", prefix, t, bucket, task_name)
        except Exception as ex:
            self._logger.error(ERR_CREATING_TASK_OBJECT, task_name, bucket, prefix, ex) 
Example 15
Project: aws-ops-automator   Author: awslabs   File: task_configuration.py    License: Apache License 2.0 6 votes vote down vote up
def remove_stack_event_topic_permissions(self):
        """
        Removes all permissions for accounts for putting events on the event bus of the Ops Automator account.
        Only permissions created by this stack are removed.
        :return:
        """

        topic_arn = os.getenv(handlers.ENV_EVENTS_TOPIC_ARN)
        sns_client = boto_retry.get_client_with_retries("sns",
                                                        methods=["remove_permission", "get_topic_attributes"],
                                                        context=self._context)

        statement = json.loads(sns_client.get_topic_attributes_with_retries(
            TopicArn=topic_arn).get("Attributes", {}).get("Policy", "{}")).get("Statement", [])

        permission_sids_for_stack = [s["Sid"] for s in statement
                                     if s["Sid"].startswith(TaskConfiguration._event_bus_permissions_sid_prefix())]

        for label in permission_sids_for_stack:
            sns_client.remove_permission_with_retries(Label=label, TopicArn=topic_arn) 
Example 16
Project: aws-ops-automator   Author: awslabs   File: task_tracking_table.py    License: Apache License 2.0 6 votes vote down vote up
def _run_local_stream_event(table, table_action, new_item, old_item=None, context=None):

        # if not running in lambda environment create event that normally results from dynamodb inserts and pass directly
        # to the main lambda handler to simulate an event triggered by the dynamodb stream

        if old_item is None:
            old_item = {}
        account = os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT)
        region = services.get_session().region_name
        event = {
            "Records": [
                {
                    "eventName": table_action,
                    "eventSourceARN": "arn:aws:dynamodb:{}:{}:table/{}/stream/{}".format(region, account, table,
                                                                                         datetime.utcnow().isoformat()),
                    "eventSource": "aws:dynamodb",
                    "dynamodb": {
                        "NewImage": build_record(new_item),
                        "OldImage": build_record(old_item)
                    }
                }]
        }

        handler = handlers.get_class_for_handler("TaskTrackingHandler")(event, context)
        handler.handle_request() 
Example 17
Project: indras_net   Author: gcallah   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_prop_path(model_name, model_dir="models"):
    ihome = os.getenv("INDRA_HOME", " ")
    return ihome + "/" + model_dir + "/props/" + model_name + ".props.json" 
Example 18
Project: indras_net   Author: gcallah   File: env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, action=None, random_placing=True,
                 serial_obj=None,
                 exclude_member=None,
                 census=None,
                 line_data_func=None,
                 pop_hist_setup=None,
                 pop_hist_func=None,
                 members=None,
                 reg=True,
                 **kwargs):
        super().__init__(name, action=action,
                         random_placing=random_placing, serial_obj=serial_obj,
                         reg=False, members=members, **kwargs)

        self.type = type(self).__name__
        self.user_type = os.getenv("user_type", TERMINAL)
        # this func is only used once, so no need to restore it
        self.pop_hist_setup = pop_hist_setup

        self.num_switches = 0
        if serial_obj is not None:
            # are we restoring env from json?
            self.restore_env(serial_obj)
        else:
            self.construct_anew(line_data_func, exclude_member,
                                census, pop_hist_func)

        self.set_menu_excludes()

        # now we set our global singleton:
        regis.set_env(self) 
Example 19
Project: indras_net   Author: gcallah   File: test_env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_line_data(self):
        """
        Test the construction of line graph data.
        This test must be changed to handle new color param!
        Commented out for the moment.
        """
        global travis
        travis = os.getenv("TRAVIS")
        if not travis:
            self.env.pop_hist = self.fill_pop_hist()
            ret = self.env.line_data()
            self.assertEqual(ret, (2,
                                   {GRP1: {"color": "navy", "data": [10, 20]},
                                    GRP2: {"color": "blue", "data": [10, 20]}})) 
Example 20
Project: indras_net   Author: gcallah   File: test_env.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_plot_data(self):
        """
        Test the construction of scatter plot data.
        """
        global travis
        travis = os.getenv("TRAVIS")
        if not travis:
            our_grp = Composite(GRP1, members=[self.newton])
            self.env = Env("Test env", members=[our_grp])
            ret = self.env.plot_data()
            (x, y) = self.newton.pos
            self.assertEqual(ret, {GRP1: {X: [x], Y: [y], 'color': None,
                                          'marker': None}}) 
Example 21
Project: clikit   Author: sdispater   File: terminal.py    License: MIT License 5 votes vote down vote up
def width(self):
        width = os.getenv("COLUMNS", "").strip()
        if width:
            return int(width)

        if self._width is None:
            self._init_dimensions()

        return self._width 
Example 22
Project: clikit   Author: sdispater   File: terminal.py    License: MIT License 5 votes vote down vote up
def height(self):
        height = os.getenv("LINES", "").strip()
        if height:
            return int(height)

        if self._height is None:
            self._init_dimensions()

        return self._height 
Example 23
Project: drydock   Author: airshipit   File: conftest.py    License: Apache License 2.0 5 votes vote down vote up
def input_files(tmpdir_factory, request):
    tmpdir = tmpdir_factory.mktemp('data')
    samples_dir = os.path.dirname(os.getenv('YAMLDIR'))
    samples = os.listdir(samples_dir)

    for f in samples:
        src_file = samples_dir + "/" + f
        dst_file = str(tmpdir) + "/" + f
        shutil.copyfile(src_file, dst_file)

    return tmpdir 
Example 24
Project: aegea   Author: kislyuk   File: cloudinit.py    License: Apache License 2.0 5 votes vote down vote up
def get_bootstrap_files(rootfs_skel_dirs, dest="cloudinit"):
    manifest = OrderedDict()
    aegea_conf = os.getenv("AEGEA_CONFIG_FILE")
    targz = io.BytesIO()
    tar = tarfile.open(mode="w:gz", fileobj=targz) if dest == "tarfile" else None

    for rootfs_skel_dir in rootfs_skel_dirs:
        if rootfs_skel_dir == "auto":
            fn = os.path.join(os.path.dirname(__file__), "..", "rootfs.skel")
        elif aegea_conf:
            # FIXME: not compatible with colon-separated AEGEA_CONFIG_FILE
            fn = os.path.join(os.path.dirname(aegea_conf), rootfs_skel_dir)
        elif os.path.exists(rootfs_skel_dir):
            fn = os.path.abspath(os.path.normpath(rootfs_skel_dir))
        else:
            raise Exception("rootfs_skel directory {} not found".format(fn))
        logger.debug("Trying rootfs.skel: %s" % fn)
        if not os.path.exists(fn):
            raise Exception("rootfs_skel directory {} not found".format(fn))
        for root, dirs, files in os.walk(fn):
            for file_ in files:
                path = os.path.join("/", os.path.relpath(root, fn), file_)
                if dest == "cloudinit":
                    add_file_to_cloudinit_manifest(os.path.join(root, file_), path, manifest)
                elif dest == "tarfile":
                    tar.add(os.path.join(root, file_), path)

    if dest == "cloudinit":
        return list(manifest.values())
    elif dest == "tarfile":
        tar.close()
        return targz.getvalue() 
Example 25
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: convert.py    License: MIT License 5 votes vote down vote up
def main(wf):
    userId = os.getenv('userId')
    data = wf.stored_data('wechat_search_user_list')
    for item in data:
        if item['userId'] == userId:
            title = 'To:'+item['title']
            subTitle = item['subTitle']
            icon = item['icon']
            wf.add_item(title=title, subtitle=subTitle, icon=icon, valid=True, arg=sys.argv[1])
    wf.send_feedback() 
Example 26
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: userChatLog.py    License: MIT License 5 votes vote down vote up
def main(wf):
    userId = os.getenv('userId')
    baseUrl = os.getenv('baseUrl')
    url = baseUrl + 'chatlog?userId=' + userId + '&count=45'
    try:
        result = web.get(url=url)
        result.raise_for_status()
        resp = result.text
        userList = json.loads(resp)
        if len(userList) > 0:
            wf.store_data('wechat_send_content',sys.argv[1])
            for item in userList:
                title = item['title']
                subtitle = item['subTitle']
                icon = item['icon']
                userId = item['userId']
                copyText = item['copyText']
                qlurl = item['url']
                srvId = str(item['srvId'])
                titleLen = len(title)
                lineNun = 70
                if titleLen < lineNun:
                    largetext = title
                else:
                    titleArray = []
                    for n in range(titleLen):
                        if n % lineNun == 0:
                            titleArray.append(title[n:n+lineNun])
                    largetext='\n'.join(titleArray)
                wf.add_item(title=title, subtitle=subtitle, icon=icon, valid=True, largetext=largetext, quicklookurl=qlurl, copytext=copyText, arg=srvId)
        else:
            wf.add_item(title='找不到联系人…',subtitle='请重新输入')
    except IOError:
                wf.add_item(title='请先启动微信 & 登录…',subtitle='并确保安装微信小助手')

    wf.send_feedback() 
Example 27
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow3.py    License: MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        """Create a new :class:`Workflow3` object.

        See :class:`~workflow.Workflow` for documentation.

        """
        Workflow.__init__(self, **kwargs)
        self.variables = {}
        self._rerun = 0
        # Get session ID from environment if present
        self._session_id = os.getenv('_WF_SESSION_ID') or None
        if self._session_id:
            self.setvar('_WF_SESSION_ID', self._session_id) 
Example 28
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: search.py    License: MIT License 5 votes vote down vote up
def main(wf):
    query = sys.argv[1]
    baseUrl = os.getenv('baseUrl')
    url = baseUrl + 'user?keyword=' + query
    try:
        result = web.get(url=url)
        result.raise_for_status()
        resp = result.text
        userList = json.loads(resp)
        if len(userList) > 0:
            for item in userList:
                title = item['title']
                subtitle = item['subTitle']
                icon = item['icon']
                userId = item['userId']
                copyText = item['copyText']
                qlurl = item['url']
                wf.add_item(title=title, subtitle=subtitle, icon=icon, largetext=title, copytext=copyText, quicklookurl=qlurl, arg=userId, valid=True)
        else:
            wf.add_item(title='找不到联系人…',subtitle='请重新输入')
    except IOError:
        wf.add_item(title='请先启动微信 & 登录…',subtitle='并确保安装微信小助手')

    wf.send_feedback() 
Example 29
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: sendMsg.py    License: MIT License 5 votes vote down vote up
def main(wf):
    srvId = sys.argv[1]
    userId = os.getenv('userId')
    baseUrl = os.getenv('baseUrl')
    msgContent = wf.stored_data('wechat_send_content')

    url = baseUrl + 'send-message'
    data = {'userId':userId, 'content': msgContent, 'srvId': srvId}
    r = web.post(url=url,data=data)
    r.raise_for_status()
    wf.send_feedback() 
Example 30
Project: btrecon   Author: jgamblin   File: btrecon.py    License: MIT License 5 votes vote down vote up
def color(text, color_code):
    if sys.platform == "win32" and os.getenv("TERM") != "xterm":
        return text

    return '\x1b[%dm%s\x1b[0m' % (color_code, text)