如何在 Linux 上像 rm -rf 一样在 Python 中强制删除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13766513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do force remove in Python like rm -rf on Linux?
提问by user1344022
I want to remove some log files of my App server without shutting down my server. What command can I use to do this using Python, like rm -rfin Linux systems?
我想在不关闭服务器的情况下删除我的应用服务器的一些日志文件。我可以使用什么命令来使用 Python 执行此操作,例如rm -rf在 Linux 系统中?
Please help.
请帮忙。
回答by RamneekHanda
#!/usr/bin/env python
import os
def nukedir(dir):
if dir[-1] == os.sep: dir = dir[:-1]
files = os.listdir(dir)
for file in files:
if file == '.' or file == '..': continue
path = dir + os.sep + file
if os.path.isdir(path):
nukedir(path)
else:
os.unlink(path)
os.rmdir(dir)
nukedir("/home/mb/test");
Above function will delete any directory recursively...
以上函数将递归删除任何目录...
回答by Alex Couper
shutil is your friend in this instance.
在这种情况下,shutil 是你的朋友。
http://docs.python.org/2/library/shutil.html#shutil.rmtree
http://docs.python.org/2/library/shutil.html#shutil.rmtree
import shutil
shutil.rmtree("/my/path/to/folder/to/destroy")
回答by Alex Couper
You can use the subprocessmodule:
您可以使用该subprocess模块:
from subprocess import Popen, PIPE, STDOUT
cmd = 'rm -frv /path/to/dir'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
out = p.stdout.read()
print out
回答by alexis
Is your server running Linux, or is that just an example?
您的服务器是否运行 Linux,或者这只是一个示例?
On python, shutil.rmtree()is the equivalent to rm -r(as @Alex already answered). All python removal commands (os.unlink(), os.rmdir()) work without checks, so they're always equivalent to rm -f.
在 python 上,shutil.rmtree()相当于rm -r(因为@Alex 已经回答了)。所有 python 删除命令 ( os.unlink(), os.rmdir()) 都无需检查即可工作,因此它们始终等效于rm -f.
But if you're on Windows, the OS will not let youdelete a file that's still open; you'll get an exception. AFAIK there's nothing an unprivileged process can do about it.
但是如果你在 Windows 上,操作系统不会让你删除一个仍然打开的文件。你会得到一个例外。AFAIK 没有特权的进程对此无能为力。

