- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在学习 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/
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 11 年前。 Improve thi
我正在尝试使用 speedtest-cli api。从官方维基复制部分代码(并删除了未使用的东西): import speedtest s = speedtest.Speedtest() s.get_
我正在尝试在 Speedtest API 上使用以下代码 def get_bytes(self): s = speedtest.Speedtest() s.ge
我正在尝试在 Speedtest API 上使用以下代码 def get_bytes(self): s = speedtest.Speedtest() s.ge
我最近开始做一个速度测试应用程序。方法很简单: 我实例化多个线程,所有线程都下载相同的不可压缩文件,然后计算平均下载速度。 但我认为存在一些性能问题。当我使用多个线程开始测试时,我在 logCat 中
我只想从bash中提取上传和下载的速度测试。我的 csv(tab) 文件有 3000++ 行,只想提取最后一行 ~ 85.41 和 9.15。 2019-03-02 11:00:02 2019
我读过很多关于将文件保存到客户端设备的临时位置的问题、答案和博客,他们都说这是不可能的。但是,如果这不可能,那么在线速度测试站点如何决定我们的互联网连接的考试速度。?? 一定有办法!! 谁能分享他/她
问题很简单。当我开始速度测试(例如 fast.com 或 speedtest.net)时,结果始终低于在 Chrome 应用程序或自定义选项卡中启动的结果,通常在 WebView 中的结果要低两倍。
我想在我的 python 程序中使用 speedtest-cli 或任何替代方法来了解我的互联网下载和上传速度。 我为此使用 Windows,speedtest-cli 似乎在命令行中运行良好,但不知
我正在学习 python,我正在尝试使用 python 运行一些终端命令行;例如:速度测试和 ping。我使用函数式编程作为我的编程方法。但是,通过基于 docs.python.org 的函数式编程阅
我是一名优秀的程序员,十分优秀!