Python程序未按预期提示用户

时间:2019-05-17 18:27:58

标签: python linux

我正在尝试编写一个程序,该程序会自动删除用户输入提供的目录。但是,执行代码时,没有提示我要删除的目录,因此实际上没有任何内容被删除或打印到屏幕上。我要去哪里错了?我想念什么吗?

尽管我得到了相同的输出,但是我尝试在函数的内部和外部添加'input'函数。我一直得到的唯一输出是打印功能中包含的内容。

from sys import argv
import subprocess
import os

print ("""This tool is designed to remove multiple or single directories from your computer. \n You'll be asked the directory of which you wish to be removed.""")

name = argv(script[0])
directoryPath = input("Enter the directory to be deleted: ")

def removeDirectory(os):
    os.system("rm -rf", directoryPath)
    if os.stat(directoryPath) == 0:
        print (directoryPath, " has been successfully deleted")
    else:
        if os.stat(directoryPath) > 0:
            print ("The directory has been removed. Try re-running the script.")

我的目的是提示用户(me)输入我要删除的目录,然后,如果成功,则打印消息“(目录)已成功删除。”

非常感谢您提出任何建议。

3 个答案:

答案 0 :(得分:2)

我认为您忘记了调用已定义的函数。这是相同的代码,换行:

from sys import argv
import subprocess
import os

# Function definition must happen before the function is called
def removeDirectory(directoryPath):
    os.system("rm -rf", directoryPath)
    if os.stat(directoryPath) == 0:
        print (directoryPath, " has been successfully deleted")
    else:
        if os.stat(directoryPath) > 0:
            print ("The directory has been removed. Try re-running the script.")

print ("""This tool is designed to remove multiple or single directories from your computer. \n You'll be asked the directory of which you wish to be removed.""")

name = argv(script[0])
directoryPath = input("Enter the directory to be deleted: ")
removeDirectory(directoryPath)      # < added this line

编辑:正如其他人指出的那样,您不应使用“ os”作为函数的参数(因为它已经被用来引用您导入的库了)。我已经在上面的代码中进行了更改。

答案 1 :(得分:1)

from sys import argv
import subprocess
import os

def removeDirectory(directoryPath):
    os.system("rm -rfi {0}".format(directoryPath))
    if os.stat(directoryPath) == 0:
        print(directoryPath, " has been successfully deleted")
    else:
        if os.stat(directoryPath) > 0:
            print("The directory has been removed. Try re-running the script.")

def main():
    print("""This tool is designed to remove multiple or single directories from your computer. \n You'll be asked the directory of which you wish to be removed.""")

    name = argv(script[0])
    directoryPath = input("Enter the directory to be deleted: ")
    removeDirectory(directoryPath)

if __name__ == "__main__":
    # execute only if run as a script
    main()

答案 2 :(得分:0)

我只想亲自感谢所有试图帮助我解决问题的人。但是,我设法找到了解决方案。而是使用功能'os.removedirs'。我使用了一个名为“ shutil.rmtree(directoryPath)”的函数,该函数在没有警告的情况下删除了输入的目录。虽然,如果没有我的帮助,我无法做到这一点,所以感谢所有参与其中的人!