rm rf不通过python fork execl scrip删除目录

2024-09-25 00:31:20 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我正在尝试使用python的fork和execl来创建一个新的bash进程并删除一个目录'testdir'。你知道吗

我编写了以下代码:

import os

pid = os.fork()
if pid == 0:
    os.execl('/bin/rm', 'rm-rf', 'temptdir') # temptdir is a directory in home folder. 

我希望它将创建一个新的bash进程,并在bash中运行以下命令:

rm -rf temptdir

删除目录,但它显示:

rm-rf: temptdir: is a directory

知道为什么不删除目录吗?又该如何修复呢?

最后,在python文档中,python execl命令的fortmat为:

execl(  path, arg0, arg1, ...)

但如果我跑了:

os.execl('/bin/echo','hello')

它不打印任何东西。为什么我必须添加一个额外的'echo'参数,例如:

os.execl('/bin/echo','echo','hello')

Tags: rm命令echo目录bashbin进程is
2条回答

试试这个:最好检查执行删除或删除操作的路径。。你知道吗

import shutil
import os
dct = "testrmo"
if os.path.exists(dct):
    os.rmdir(dct)   # <   if directory is blank
    #shutil.rmtree(dct) # <- - if directory has the contents
else:
    print("Sorry, I can not remove %s Dir." % dct)


shutil.rmtree() deletes a directory and all its contents.

更好地使用子流程:

import subprocess
subprocess.call(['rm', '-rf', 'temptdir'])

顺便说一下,在玩文件和目录时使用os模块

os.remove() removes a file.

os.rmdir() removes an empty directory.

shutil.rmtree() deletes a directory and all its contents.

pathlib.Path.unlink() removes the file or symbolic link.

pathlib.Path.rmdir() removes the empty directory.

另一种方法是,如果您需要像本机方法一样删除它:

os.system('rm -rf /your_directory_path/')

你需要分别传递参数。因为-rfrm的独立参数。你知道吗

import os

pid = os.fork()
if pid == 0:
    os.execl('/bin/rm', 'rm', '-rf', 'temptdir') # temptdir is a directory in home folder.

相关问题 更多 >