我编写了一个命令行工具,以git pull使用python asyncio 执行多个git repos。如果所有存储库均具有ssh无需密码的登录设置,则该方法可以正常工作。如果仅1个回购协议需要输入密码,它也可以正常工作。当多个存储库需要输入密码时,它似乎陷入僵局。
我的实现非常简单。主要逻辑是
utils.exec_async_tasks(
utils.run_async(path, cmds) for path in repos.values())
Run Code Online (Sandbox Code Playgroud)
在这里run_async创建并等待子流程调用,然后exec_async_tasks运行所有任务。
async def run_async(path: str, cmds: List[str]):
"""
Run `cmds` asynchronously in `path` directory
"""
process = await asyncio.create_subprocess_exec(
*cmds, stdout=asyncio.subprocess.PIPE, cwd=path)
stdout, _ = await process.communicate()
stdout and print(stdout.decode())
def exec_async_tasks(tasks: List[Coroutine]):
"""
Execute tasks asynchronously
"""
# TODO: asyncio API is nicer in python 3.7
if platform.system() == 'Windows':
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(asyncio.gather(*tasks)) …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用scp(安全复制)命令subprocess.Popen.登录要求我发送密码:
from subprocess import Popen, PIPE
proc = Popen(['scp', "user@10.0.1.12:/foo/bar/somefile.txt", "."], stdin = PIPE)
proc.stdin.write(b'mypassword')
proc.stdin.flush()
Run Code Online (Sandbox Code Playgroud)
这会立即返回错误:
user@10.0.1.12's password:
Permission denied, please try again.
Run Code Online (Sandbox Code Playgroud)
我确定密码是正确的.我通过手动调用scpshell 轻松验证它.那么为什么这不起作用呢?
请注意,有许多类似的问题,询问subprocess.Popen并发送自动SSH或FTP登录的密码:
如何从python脚本在linux中设置用户密码?
使用子进程发送密码
这些问题的答案不起作用和/或不适用,因为我使用的是Python 3.
我正在使用 asyncio subprocess 来执行子命令。我想查看长时间运行的进程并同时将内容保存到缓冲区以供以后使用。此外,我发现了这个相关的问题(Getting live output from asyncio subprocess),但它主要围绕 ssh 的用例。
asyncio subprocess 文档有一个逐行读取输出的示例,这符合我想要实现的目标。(https://docs.python.org/3/library/asyncio-subprocess.html#examples)
import asyncio
import sys
async def get_date():
code = 'import datetime; print(datetime.datetime.now())'
# Create the subprocess; redirect the standard output
# into a pipe.
proc = await asyncio.create_subprocess_exec(
sys.executable, '-c', code,
stdout=asyncio.subprocess.PIPE)
# Read one line of output.
data = await proc.stdout.readline()
line = data.decode('ascii').rstrip()
# Wait for the subprocess exit.
await proc.wait()
return line
date = asyncio.run(get_date())
print(f"Current date: {date}")
Run Code Online (Sandbox Code Playgroud)
我将此示例改编为以下内容: …