关于第一个问题,直接在函数中执行命令而不在函数中使用参数/参数是没有问题的。在
例如,您可以在函数定义中添加一个参数来指定路径,以便可以调用函数并使用不同的目录执行命令: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官方文档(python3.6),存在一个os.system的升级版本^{}: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:
^{pr2}$