简体   繁体   English

哪个命令更好:os.listdir() 或 os.system('ls') 以及为什么?

[英]which command is better: os.listdir() or os.system('ls') and WHY?

In the current working directory:在当前工作目录中:

import os
print( os.listdir() )

will list the files and directories.将列出文件和目录。 However, I could also get a list of the files and directories in the current working directory of a Linux machine using the system command:但是,我也可以使用system命令获取 Linux 机器当前工作目录中的文件和目录列表:

import os
print( os.system('ls') )

Which command is better: os.listdir() or os.system('ls') and why?哪个命令更好: os.listdir()os.system('ls') ,为什么?

os.listdir() is implemented natively in python, and will work on any operating system that python is compiled on. os.listdir()是在 python 中本地实现的,并且可以在任何编译 python 的操作系统上运行。

Calling os.system('ls') relies on the underlying operating system to have an ls command, which is a wild assumption (eg, what about windows?), and requires this executable to be in the $PATH .调用os.system('ls')依赖于底层操作系统有一个ls命令,这是一个疯狂的假设(例如,windows 怎么样?),并且需要这个可执行文件在$PATH From a performance standpoint, you'd be executing another process, which is completely redundant.从性能的角度来看,您将执行另一个完全多余的进程。 And if you want to do anything fancier than just printing the result, you'll have to mess around with parsing the output yourself.如果你想做任何比打印结果更有趣的事情,你将不得不自己解析输出。

To make a long story short - don't reinvent the wheel.长话短说 - 不要重新发明轮子。 If python gives you a built-in os.listdir() , just use it.如果 python 给你一个内置的os.listdir() ,就使用它。

I maybe digging graves here but I recently came across a similar usage.我可能在这里挖坟,但我最近遇到了类似的用法。

I tried to ls a /path/to/temp file.我试图ls一个/path/to/temp文件。 It did not work, the ls command would get stuck and unresponsive, for more than 5 minutes before I shut it down.它不起作用,在我关闭它之前ls命令会卡住并且没有响应超过 5 分钟。 notice this was over SSH via putty, I tried ls -l | wc -l注意这是通过腻子通过 SSH,我试过ls -l | wc -l ls -l | wc -l , which didn't work either. ls -l | wc -l ,这也不起作用。

len(os.listdir("path/to/temp")) returned a number immediately, and it was around 75000 , the list was constructed nearly immediately. len(os.listdir("path/to/temp"))立即返回一个数字,大约是75000 ,该列表几乎立即构建。 So there is a clear speed advantage if you use os.listdir() vs ls on directory with a large number of descendants.因此,如果您在具有大量后代的目录上使用os.listdir()与 ls ,则有明显的速度优势。

Just to pile on: ls has an overhead limit to the number of files in the directory you are trying to use it on.只是为了堆积: ls对您尝试使用它的目录中的文件数量有一个开销限制。 os.listdir() suffers no such limitation. os.listdir()没有这样的限制。 If you can use it, then os.listdir() seems to be the superior choice.如果你可以使用它,那么os.listdir()似乎是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM