我有一个函数,它异步运行一个子进程命令并返回结果。它看起来是这样的:
import asyncio
async def async_subprocess_command(*args):
# Create subprocess
process = await asyncio.create_subprocess_exec(
*args,
# stdout and stderr must a pipe to be accessible as process.stdout
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
#Remove final carriage return from string
stdout_formatted = stdout.decode().strip().replace('\r', '')
stderr_formatted = stderr.decode().strip().replace('\r', '')
# Return stdout and sterr
return stdout_formatted, stderr_formatted如果我能够同步工作,我倾向于使用对子流程模块的调用:
import subprocess
subprocess.getoutput([parameter1,parameter2,parameter3])当我同步调用subprocess.getoutput时(假设我正在调用一个外部工具),没有打开任何控制台窗口。当我异步调用asyncio.create_subprocess_exec时(同样,假设我调用的是一个外部工具),每次调用它时都会弹出一个控制台窗口,这会使计算机在异步调用完成之前很难与之交互。
有没有办法在不弹出控制台窗口的情况下异步调用asyncio.create_subprocess_exec?
发布于 2017-08-20 20:08:31
使用eryksun的建议,我能够使用带有额外参数(creationflags=DETACHED_PROCESS)的原始函数。它比第一个答案中使用asyncio.create_subprocess_shell函数的速度稍快一些,并按预期工作。有关其他好处的更多信息,请参见上面的eryksun评论。
async def async_subprocess_command(*args):
#CREATE_NO_WINDOW = 0x08000000 using detatched_process is slightly faster
DETACHED_PROCESS = 0x00000008
# Create subprocess
process = await asyncio.create_subprocess_exec(
*args,
# stdout and stderr must a pipe to be accessible as process.stdout
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
creationflags=DETACHED_PROCESS,
)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
#Remove final carriage return from string
stdout_formatted = stdout.decode().strip().replace('\r', '')
stderr_formatted = stderr.decode().strip().replace('\r', '')
# Return stdout and sterr
return stdout_formatted, stderr_formatted发布于 2017-08-20 07:47:16
我在另一个函数中找到了答案:
async def async_subprocess_command(cmd):
'''
cmd should be a string exactly as you
write into the cmd line
'''
process = await asyncio.create_subprocess_shell(cmd,
stdin=None, stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
stdout_formatted = stdout.decode().strip().replace('\r', '')
stderr_formatted = stderr.decode().strip().replace('\r', '')
return stdout_formatted, stderr_formattedhttps://stackoverflow.com/questions/45769985
复制相似问题