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

Create a python function to run speedtest-cli/ping in terminal and output result to a log file

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

我的问题是:
函数没有 argument/parameters 直接在里面输入 command/s 好吗?
使用 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()

使用 wiki

中详述的 speedtest-cli API

(以下来自 wiki 的代码)

import speedtest

servers = []
# If you want to test against a specific server
# servers = [1234]

s = speedtest.Speedtest()
s.get_servers(servers)
s.get_best_server()
s.download()
s.upload()
s.results.share()

results_dict = s.results.dict()

有关 python 中的 ping,请参阅 this question and many answers

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

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

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更好的模块。

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

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

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

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

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