gpt4 book ai didi

python - 创建一个 python 函数以在终端中运行 speedtest-cli/ping 并将结果输出到日志文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:50 25 4
gpt4 key购买 nike

我正在学习 python,我正在尝试使用 python 运行一些终端命令行;例如:速度测试和 ping。我使用函数式编程作为我的编程方法。但是,通过基于 docs.python.org 的函数式编程阅读和浏览更多内容后 1 .我认为我的做法不对。

我的问题是:
一个函数没有参数,直接在里面输入命令好吗?
使用 os.system 真的是一个不错的选择还是有更好的模块可以使用?

这是我的代码示例。

#!/usr/bin/python3
# tasks.py

import os

def task_speedtest():
os.system("speedtest-cli >> /Desktop/logs")

def task_ping():
os.system("ping www.google.com -c5 >> /Desktop/logs")

task_speedtest()
task_ping()

最佳答案

关于你的第一个问题,在你的函数中不使用参数/参数直接执行函数中的命令没有错。

你总是可以在你的函数定义中添加一个参数来指定路径,例如这样你就可以调用函数并使用不同的目录执行命令:

def task_speedtest(path):
os.system("speedtest-cli >> " + path)

def task_ping():
os.system("ping www.google.com -c5 >> " + path)

path = "/Desktop/logs"
task_speedtest(path)
task_ping(path)

关于你的第二个问题,是的,有比 os.system 更好的模块。

存在 os.system 的升级版本 Subprocess ,根据官方 Python 文档 (Python 3.6):

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions.

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle.

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance

甚至有一节介绍如何用新的子进程替换 os.system here :

sts = os.system("mycmd" + " myarg")
# becomes
sts = call("mycmd" + " myarg", shell=True)

我建议您在 Subprocess 的官方 Python 文档中阅读有关新模块的更多信息:https://docs.python.org/3.6/library/subprocess.html

关于python - 创建一个 python 函数以在终端中运行 speedtest-cli/ping 并将结果输出到日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com