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