當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。