当前位置: 首页>>代码示例>>Python>>正文


Python asyncio.create_subprocess_shell方法代码示例

本文整理汇总了Python中asyncio.create_subprocess_shell方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.create_subprocess_shell方法的具体用法?Python asyncio.create_subprocess_shell怎么用?Python asyncio.create_subprocess_shell使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在asyncio的用法示例。


在下文中一共展示了asyncio.create_subprocess_shell方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _record_perf_async

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def _record_perf_async(
        loop: asyncio.BaseEventLoop, event: str, message: str) -> None:
    """Record timing metric async
    :param asyncio.BaseEventLoop loop: event loop
    :param str event: event
    :param str message: message
    """
    if not _RECORD_PERF:
        return
    proc = await asyncio.create_subprocess_shell(
        './perf.py cascade {ev} --prefix {pr} --message "{msg}"'.format(
            ev=event, pr=_PREFIX, msg=message), loop=loop)
    await proc.wait()
    if proc.returncode != 0:
        logger.error(
            'could not record perf to storage for event: {}'.format(event)) 
开发者ID:Azure,项目名称:batch-shipyard,代码行数:18,代码来源:cascade.py

示例2: start

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def start(self):
        if self.is_active:
            print(f"[Cluster {self.id}] Already active.")
            return
        self.started_at = time.time()
        self._process = await asyncio.create_subprocess_shell(
            self.command,
            stdin=asyncio.subprocess.DEVNULL,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            preexec_fn=os.setsid,
            limit=1024 * 256,
        )
        self.status = "running"
        self.started_at = time.time()
        print(f"[Cluster {self.id}] The cluster is starting.")
        await asyncio.wait([self.read_stream(self._process.stdout), self.read_stream(self._process.stderr)])
        return self 
开发者ID:CHamburr,项目名称:modmail,代码行数:20,代码来源:launcher.py

示例3: wait_for_pulseaudio_startup

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def wait_for_pulseaudio_startup(self, vm):
        self.loop.run_until_complete(
            self.wait_for_session(self.testvm1))
        try:
            self.loop.run_until_complete(vm.run_for_stdio(
                "timeout 30s sh -c 'while ! pactl info; do sleep 1; done'"
            ))
        except subprocess.CalledProcessError as e:
            self.fail('Timeout waiting for pulseaudio start in {}: {}{}'.format(
                vm.name, e.stdout, e.stderr))
        # then wait for the stream to appear in dom0
        local_user = grp.getgrnam('qubes').gr_mem[0]
        p = self.loop.run_until_complete(asyncio.create_subprocess_shell(
            "sudo -E -u {} timeout 30s sh -c '"
            "while ! pactl list sink-inputs | grep -q :{}; do sleep 1; done'".format(
                local_user, vm.name)))
        self.loop.run_until_complete(p.wait())
        # and some more...
        self.loop.run_until_complete(asyncio.sleep(1)) 
开发者ID:QubesOS,项目名称:qubes-core-admin,代码行数:21,代码来源:vm_qrexec_gui.py

示例4: shell

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def shell(self, request, command, communicate=None,
                    raw=False, chdir=None):
        """Asynchronous execution of a shell command
        """
        if chdir:
            command = 'cd %s && %s' % (chdir, command)
        request.logger.info('Execute shell command: %s', command)
        stdin = subprocess.PIPE if communicate else None
        proc = await create_subprocess_shell(command,
                                             stdin=stdin,
                                             stdout=subprocess.PIPE,
                                             stderr=subprocess.PIPE)
        if communicate:
            msg, err = await proc.communicate(to_bytes(communicate))
        else:
            await proc.wait()
            msg = await proc.stdout.read()
            err = await proc.stderr.read()
        if proc.returncode:
            err = err.decode('utf-8').strip()
            raise ShellError(err, proc.returncode)
        return msg if raw else msg.decode('utf-8').strip() 
开发者ID:quantmind,项目名称:lux,代码行数:24,代码来源:app.py

示例5: compile

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def compile(self, prior_output: FilePath, compile_command: str) -> FilePath:
        # prior_output is the location where our new file will be created after compiling
        # compile_command is the thing we're going to execute (hopefully after some pre-processing is done)
        proc = await asyncio.create_subprocess_shell(compile_command,
                                                     stdout=asyncio.subprocess.PIPE,
                                                     stderr=asyncio.subprocess.PIPE,
                                                     cwd=self.working_dir)
        stdout, stderr = await proc.communicate()
        if stdout:
            print(f'[stdout]\n{stdout.decode()}')
        if stderr:
            print(f'[stderr]\n{stderr.decode()}')
            raise Exception(stderr.decode())
        # we return the status (in case that's something you want to print out) and where the new file is located
        print("called compile and returned final path of: {}".format(prior_output))
        return FilePath(prior_output) 
开发者ID:its-a-feature,项目名称:Apfell,代码行数:18,代码来源:utils.py

示例6: call_method

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def call_method(
            self, method, arg_signature, args, return_signature, returns
    ):
        cmd = 'busctl --user -- call '
        cmd += f'{service_name} {object_path} {object_interface} {method}'
        cmd += f' "{arg_signature}"'
        for i in args:
            cmd += f' {i}'

        create = asyncio.create_subprocess_shell(
                cmd, stdout=asyncio.subprocess.PIPE
        )

        proc = await create

        # Read one line of output
        data = await proc.stdout.readline()
        line = data.decode('ascii').rstrip()

        self.assertEqual(line, f'{return_signature} {returns}')

        await proc.wait() 
开发者ID:ccxtechnologies,项目名称:adbus,代码行数:24,代码来源:test_server.py

示例7: cat

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def cat(loop):

    #
    # 异步返回:
    #   - 调用接口:
    #
    proc = yield from asyncio.create_subprocess_shell("cat",
                                                      stdin=PIPE,
                                                      stdout=PIPE)
    print("pid: %s" % proc.pid)

    message = "Hello World!"
    print("cat write: %r" % message)

    stdout, stderr = yield from proc.communicate(message.encode('ascii'))
    print("cat read: %r" % stdout.decode('ascii'))

    exitcode = yield from proc.wait()
    print("(exit code %s)" % exitcode) 
开发者ID:hhstore,项目名称:annotated-py-projects,代码行数:21,代码来源:shell.py

示例8: aria_start

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def aria_start(event):
    process = await asyncio.create_subprocess_shell(
        aria2_daemon_start_cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()
    global aria2
    aria2 = aria2p.API(
        aria2p.Client(
            host="http://localhost",
            port=ARIA2_STARTED_PORT,
            secret=""
        )
    )
    OUTPUT = f"**ARIA TWO C:**\n__PID:__\n`{process.pid}`\n\n**ARIA TWO STARTED**"
    await event.edit(OUTPUT) 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:19,代码来源:aria_two.py

示例9: sysdetails

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def sysdetails(sysd):
    """ a. """
    if not sysd.text[0].isalpha() and sysd.text[0] not in ("/", "#", "@", "!"):
        try:
            neo = "neofetch/neofetch --on --color_blocks on --bold on --cpu_temp=C \
                    --cpu_speed on --cpu_cores physical --kernel_shorthand on \
                    --gpu_brand on --refresh_rate on --gtk_shorthand on --colors=distro  --backend ascii \
                    --source=auto --Redhat source --stdout"
            fetch = await asyncrunapp(
                neo,
                stdout=asyncPIPE,
                stderr=asyncPIPE,
            )

            stdout, stderr = await fetch.communicate()
            result = str(stdout.decode().strip()) \
                + str(stderr.decode().strip())

            await sysd.edit("sysd Result: `" + result + "`")
        except FileNotFoundError:
            await sysd.edit("`Hey, on mkaraniya/BotHub install .neofetch first kthx`") 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:23,代码来源:sysd.py

示例10: runcmd

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def runcmd(self, message, cmd, editor=None):
        if len(cmd.split(" ")) > 1 and cmd.split(" ")[0] == "sudo":
            needsswitch = True
            for word in cmd.split(" ", 1)[1].split(" "):
                if word[0] != "-":
                    break
                if word == "-S":
                    needsswitch = False
            if needsswitch:
                cmd = " ".join([cmd.split(" ", 1)[0], "-S", cmd.split(" ", 1)[1]])
        sproc = await asyncio.create_subprocess_shell(cmd, stdin=asyncio.subprocess.PIPE,
                                                      stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
                                                      cwd=utils.get_base_dir())
        if editor is None:
            editor = SudoMessageEditor(message, cmd, self.config)
        editor.update_process(sproc)
        self.activecmds[hash_msg(message)] = sproc
        await editor.redraw(True)
        await asyncio.gather(read_stream(editor.update_stdout, sproc.stdout, self.config["FLOOD_WAIT_PROTECT"]),
                             read_stream(editor.update_stderr, sproc.stderr, self.config["FLOOD_WAIT_PROTECT"]))
        await editor.cmd_ended(await sproc.wait())
        del self.activecmds[hash_msg(message)] 
开发者ID:friendly-telegram,项目名称:modules-repo,代码行数:24,代码来源:terminal.py

示例11: start

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def start(self):
        """ Launch the task and readers of stdout, stderr """
        try:
            self.command = ['amass', 'enum' '-d'] + [self.target] + [self.params['program']['argv']]
            print(' '.join(self.command))
            self.proc = await asyncio.create_subprocess_shell(' '.join(self.command), stdout=PIPE, stderr=PIPE)

            # 1337 is hardcoded to show frontend that we don't track progress here
            await self.set_status("Working", progress=1337)
    
            # Launch readers
            loop = asyncio.get_event_loop()
            loop.create_task(self.read_stdout())
            loop.create_task(self.read_stderr())

        except Exception as exc:
            print(str(exc))
            self.logger.error(str(exc))
            await self.set_status("Aborted", 0, str(exc)) 
开发者ID:c0rvax,项目名称:project-black,代码行数:21,代码来源:amass_task.py

示例12: start

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def start(self):
        """ Launch the task and readers of stdout, stderr """
        print(self.params, self.target)
        try:
            self.command = ['sudo', 'masscan'] + [','.join(self.target)] + ['-oX', '-'] + self.params['program']

            self.proc = await asyncio.create_subprocess_shell(' '.join(self.command), stdout=PIPE, stderr=PIPE)

            await self.set_status("Working", progress=0)
    
            # Launch readers
            loop = asyncio.get_event_loop()
            loop.create_task(self.read_stdout())
            loop.create_task(self.read_stderr())

            # Launch status poller
            loop.create_task(self.spawn_status_poller())
        except Exception as exc:
            await self.set_status("Aborted", 0, str(exc)) 
开发者ID:c0rvax,项目名称:project-black,代码行数:21,代码来源:masscan_task.py

示例13: _

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def _(event):
    if event.fwd_from:
        return
    await event.edit("Processing ...")
    PROCESS_RUN_TIME = 100
    input_str = event.pattern_match.group(1)
    selected_transfer = event.pattern_match.group(2)
    if input_str:
        file_name = input_str
    else:
        reply = await event.get_reply_message()
        file_name = await bot.download_media(reply.media, Var.TEMP_DOWNLOAD_DIRECTORY)
    reply_to_id = event.message.id
    CMD_WEB = {"anonfiles": "curl -F \"file=@{}\" https://anonfiles.com/api/upload", "transfer": "curl --upload-file \"{}\" https://transfer.sh/{os.path.basename(file_name)}", "filebin": "curl -X POST --data-binary \"@test.png\" -H \"filename: {}\" \"https://filebin.net\"", "anonymousfiles": "curl -F file=\"@{}\" https://api.anonymousfiles.io/", "megaupload": "curl -F \"file=@{}\" https://megaupload.is/api/upload", "bayfiles": ".exec curl -F \"file=@{}\" https://bayfiles.com/api/upload"}
    try:
        selected_one = CMD_WEB[selected_transfer].format(file_name)
    except KeyError:
        await event.edit("Invalid selected Transfer")
    cmd = selected_one
    start_time = time.time() + PROCESS_RUN_TIME
    process = await asyncio.create_subprocess_shell(
        cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await process.communicate()
    await event.edit(f"{stdout.decode()}") 
开发者ID:Dark-Princ3,项目名称:X-tra-Telegram,代码行数:27,代码来源:webupload.py

示例14: output_of

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def output_of(*cmd: Optional[str], **kwargs) -> str:
    """Invokes a subprocess and returns its output as a string.

    Args:
        cmd: Components of the command to execute, e.g. ["echo", "dog"].
        **kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
            a cwd (current working directory) argument.

    Returns:
        A (captured output, captured error output, return code) triplet. The
        captured outputs will be None if the out or err parameters were not set
        to an instance of TeeCapture.

    Raises:
         subprocess.CalledProcessError: The process returned a non-zero error
            code and raise_on_fail was set.
    """
    result = cast(str, run_cmd(*cmd,
                               log_run_to_stderr=False,
                               out=TeeCapture(),
                               **kwargs).out)

    # Strip final newline.
    if result.endswith('\n'):
        result = result[:-1]

    return result 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:29,代码来源:shell_tools.py

示例15: close

# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_subprocess_shell [as 别名]
def close(self) -> None:
        try:
            p = await asyncio.create_subprocess_shell('git pull')
            await p.wait()
            p = await asyncio.create_subprocess_shell(f'{sys.executable} -m pip install -U -r requirements.txt --no-cache')
            await p.wait()
        except Exception as c: # pylint: disable=broad-except
            repo.create_issue('Bot error while closing', 'discord user', 'discordbot', 'PennyDreadfulMTG/perf-reports', exception=c)
        await super().close() 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:11,代码来源:bot.py


注:本文中的asyncio.create_subprocess_shell方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。