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

标签 python python-3.x os.system

我正在学习 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

甚至有一节介绍如何用新的子进程 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

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

相关文章:

python - 如何使用 seaborn 创建多线图?

django - 无法创建 django_migrations 表 (ORA-02000 : missing ALWAYS keyword)

python - 使用本地文件作为 set_image 文件 discord.py

Python链表打印时接收内存地址的问题除非双重调用

python - 在 Python 中按照给定的 UID 执行 shell 命令

python - 使用 Python 子进程而不是 os.system

python - 如何确定通过 os.system 启动的进程的 pid

python - 存储在 cStringIO 数据结构与物理磁盘文件中的导入模块

python - Excel错误可能是pandas写的还是大数据导致的?需要建议

python - 将 Cython 扩展类型方法传递给纯 C 函数