python3异步执行linux命令
-
Python3中可以使用`subprocess`模块来执行Linux命令。
异步执行Linux命令的步骤如下:
1. 导入`subprocess`模块:首先,我们需要在Python脚本中导入`subprocess`模块,以便于使用其中的命令执行函数。
“`python
import subprocess
“`2. 创建子进程:通过`subprocess.Popen`函数创建一个子进程,该函数接受一个字符串参数,表示要执行的命令。
“`python
process = subprocess.Popen(‘command’, shell=True)
“`其中,`command`是要执行的Linux命令。通过`shell=True`参数,我们可以使用shell语法来执行命令。
3. 等待命令执行完成:使用`process.wait()`方法来等待命令执行完成。该方法会阻塞当前进程,直到子进程执行完毕。
“`python
process.wait()
“`4. 获取命令执行结果:要获取命令执行的输出结果,可以使用`process.communicate()`方法。该方法会返回一个元组,包含了命令的输出结果和错误信息。
“`python
output, error = process.communicate()
“`其中,`output`是命令的输出结果,而`error`是错误信息(如果有)。
通过上述步骤,我们就可以在Python3中异步执行Linux命令了。下面是一个完整的示例代码:
“`python
import subprocessdef run_command_async(command):
process = subprocess.Popen(command, shell=True)
process.wait()
output, error = process.communicate()
return output.decode(‘utf-8’)command = ‘ls -l’
result = run_command_async(command)
print(result)
“`以上代码中,我们定义了一个`run_command_async`函数,用于异步执行Linux命令。在示例中,我们执行了`ls -l`命令,并打印了命令的输出结果。
需要注意的是,在执行命令时,请谨慎使用`shell=True`参数,以避免潜在的安全问题。
2年前 -
Python是一种功能强大的编程语言,它具有执行异步任务的能力。下面是在Python 3中异步执行Linux命令的几种方法:
1. 使用subprocess模块:subprocess模块是Python中执行外部进程的标准库。你可以使用subprocess模块来启动一个新的进程,并执行任意的Linux命令。可以通过使用asyncio库来异步执行多个Linux命令。以下是一个示例代码:
“`python
import asyncio
import subprocessasync def run_command(command):
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)stdout, stderr = await proc.communicate()
return stdout, stderrasync def main():
commands = [
“ls -l”,
“pwd”,
“echo ‘Hello, World!'”
]tasks = [run_command(cmd) for cmd in commands]
results = await asyncio.gather(*tasks)for cmd, result in zip(commands, results):
stdout, stderr = result
print(f”Command: {cmd}”)
if stdout:
print(f”Stdout: {stdout.decode().strip()}”)
if stderr:
print(f”Stderr: {stderr.decode().strip()}”)
print()if __name__ == “__main__”:
asyncio.run(main())
“`2. 使用aiohttp库:aiohttp是一个用于异步HTTP请求的库,也可以用来执行Linux命令。你可以通过创建Web服务器来接收HTTP请求,然后执行相应的Linux命令,并将结果返回给客户端。以下是一个示例代码:
“`python
import aiohttp
import asyncioasync def execute_command(request):
command = await request.text()
proc = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)stdout, stderr = await proc.communicate()
return aiohttp.web.Response(
text=f”Command: {command}\nStdout: {stdout.decode().strip()}\nStderr: {stderr.decode().strip()}”)async def main():
app = aiohttp.web.Application()
app.router.add_post(‘/’, execute_command)
runner = aiohttp.web.AppRunner(app)
await runner.setup()
site = aiohttp.web.TCPSite(runner, ‘localhost’, 8080)
await site.start()
print(“Web server started”)if __name__ == “__main__”:
asyncio.run(main())
“`3. 使用paramiko库:paramiko是一个用于SSH连接的Python库,可以通过SSH连接到远程服务器,并在远程服务器上执行Linux命令。以下是一个示例代码:
“`python
import asyncio
import paramikoasync def execute_command(host, username, password, command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
await asyncio.sleep(0.1) # 加入短暂延迟,避免连接问题
client.connect(host, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)stdout_data = stdout.read().decode().strip()
stderr_data = stderr.read().decode().strip()return stdout_data, stderr_data
async def main():
commands = [
(‘localhost’, ‘username’, ‘password’, ‘ls -l’),
(‘localhost’, ‘username’, ‘password’, ‘pwd’),
(‘localhost’, ‘username’, ‘password’, ‘echo “Hello, World!”‘)
]tasks = [execute_command(*cmd) for cmd in commands]
results = await asyncio.gather(*tasks)for cmd, result in zip(commands, results):
stdout, stderr = result
print(f”Command: {cmd[3]}”)
if stdout:
print(f”Stdout: {stdout}”)
if stderr:
print(f”Stderr: {stderr}”)
print()if __name__ == “__main__”:
asyncio.run(main())
“`4. 使用Fabric库:Fabric是一个Python库,可以用于远程执行命令和部署任务。它使用paramiko库来建立SSH连接,并在远程主机上执行命令。以下是一个示例代码:
“`python
from fabric import Connection, task@task
def execute_command(c, command):
result = c.run(command, hide=True)
return result.stdout, result.stderr@task
def main():
commands = [
“ls -l”,
“pwd”,
“echo ‘Hello, World!'”
]with Connection(‘localhost’, user=’username’, connect_kwargs={“password”: “password”}) as c:
results = execute_command(c, commands)for cmd, result in zip(commands, results):
stdout, stderr = result
print(f”Command: {cmd}”)
if stdout:
print(f”Stdout: {stdout.strip()}”)
if stderr:
print(f”Stderr: {stderr.strip()}”)
print()if __name__ == “__main__”:
main()
“`5. 使用asyncssh库:asyncssh是一个用于SSH连接和执行命令的Python库,可以用来异步执行Linux命令。以下是一个示例代码:
“`python
import asyncio
import asyncsshasync def execute_command(host, username, password, command):
async with asyncssh.connect(host, username=username, password=password) as conn:
result = await conn.run(command, check=True)
return result.stdout, result.stderrasync def main():
commands = [
(‘localhost’, ‘username’, ‘password’, ‘ls -l’),
(‘localhost’, ‘username’, ‘password’, ‘pwd’),
(‘localhost’, ‘username’, ‘password’, ‘echo “Hello, World!”‘)
]tasks = [execute_command(*cmd) for cmd in commands]
results = await asyncio.gather(*tasks)for cmd, result in zip(commands, results):
stdout, stderr = result
print(f”Command: {cmd[3]}”)
if stdout:
print(f”Stdout: {stdout}”)
if stderr:
print(f”Stderr: {stderr}”)
print()if __name__ == “__main__”:
asyncio.run(main())
“`以上是在Python 3中异步执行Linux命令的几种方法。你可以根据自己的需求选择适合的方法来执行异步任务。无论是使用subprocess模块,还是使用aiohttp、paramiko、Fabric或asyncssh库,都可以通过适当的代码来实现异步执行Linux命令的功能。
2年前 -
Python 3提供了许多方法来异步执行Linux命令。下面将介绍几种常用的方法和操作流程。
方法1:使用asyncio和subprocess模块
使用asyncio和subprocess模块可以方便地实现异步执行Linux命令的功能。首先,引入所需的模块:“`python
import asyncio
import subprocess
“`然后,定义一个异步函数来执行命令:
“`python
async def run_command(command):
process = await asyncio.create_subprocess_shell(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = await process.communicate()
return stdout.decode().strip(), stderr.decode().strip()
“`在这个函数中,我们使用`asyncio.create_subprocess_shell()`函数来创建一个子进程,并将命令作为参数传递给它。然后,我们使用`communicate()`方法来等待子进程执行完毕,并获取输出结果。
接下来,定义一个异步函数来调用`run_command()`函数执行多个命令:
“`python
async def run_commands(commands):
tasks = []
for command in commands:
task = asyncio.ensure_future(run_command(command))
tasks.append(task)
results = await asyncio.gather(*tasks)
return results
“`在这个函数中,我们使用`asyncio.ensure_future()`函数来创建一个任务对象,并将其添加到任务列表中。然后,我们使用`asyncio.gather()`函数来等待所有任务完成,并获取结果。
最后,使用`asyncio.run()`方法来运行主函数:
“`python
if __name__ == “__main__”:
commands = [“ls”, “pwd”, “whoami”]
results = asyncio.run(run_commands(commands))
for result in results:
print(result)
“`在主函数中,我们定义了一个命令列表,然后调用`run_commands()`函数来执行这些命令,并打印结果。
方法2:使用aiohttp库和subprocess模块
另一种异步执行Linux命令的方法是使用aiohttp库和subprocess模块。首先,安装aiohttp库:“`shell
pip install aiohttp
“`然后,引入所需的模块:
“`python
import asyncio
import aiohttp
import subprocess
“`接下来,定义一个异步函数来执行命令:
“`python
async def run_command(session, command):
async with session.get(f”http://localhost:8000/command/{command}”) as response:
return await response.text()
“`在这个函数中,我们使用aiohttp库的`session.get()`方法来发送一个GET请求到`http://localhost:8000/command/{command}`,并获取响应的文本内容。
然后,定义一个异步函数来调用`run_command()`函数执行多个命令:
“`python
async def run_commands(commands):
async with aiohttp.ClientSession() as session:
tasks = []
for command in commands:
task = asyncio.ensure_future(run_command(session, command))
tasks.append(task)
results = await asyncio.gather(*tasks)
return results
“`在这个函数中,我们使用aiohttp库的`ClientSession()`方法来创建一个会话对象,并在循环中使用`asyncio.ensure_future()`函数来创建任务对象。
最后,使用`asyncio.run()`方法来运行主函数:
“`python
if __name__ == “__main__”:
commands = [“ls”, “pwd”, “whoami”]
results = asyncio.run(run_commands(commands))
for result in results:
print(result)
“`在主函数中,我们定义了一个命令列表,然后调用`run_commands()`函数来执行这些命令,并打印结果。
总结
本文介绍了使用Python 3异步执行Linux命令的两种方法:使用asyncio和subprocess模块以及使用aiohttp库和subprocess模块。这些方法都能很好地实现异步执行命令的功能,方便处理大量的命令行任务。根据实际需要选择适合的方法来使用。2年前