Программа Python не запрашивает пользователя, как ожидалось - PullRequest
0 голосов
/ 17 мая 2019

Я пытаюсь написать программу, которая автоматически удаляет каталоги, введенные пользователем. Однако, когда код выполняется, я не получаю подсказку, спрашивающую, какие каталоги я хочу удалить, поэтому на самом деле ничего не удаляется и не выводится на экран. Куда я иду не так? Я что-то упустил?

Я попытался добавить функцию ввода внутри и снаружи функции, хотя получаю одинаковый вывод. Единственный вывод, который я продолжаю получать, - это то, что содержится в функции печати. ​​

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.")

Моя цель - запросить у пользователя (меня) каталог, который я хочу удалить, затем в случае успеха напечатайте сообщение «(каталог) был успешно удален».

Ответы [ 3 ]

2 голосов
/ 17 мая 2019

Я думаю, что вы забыли вызвать функцию, которую вы определили. Вот тот же код с новой строкой:

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 голос
/ 17 мая 2019
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()
0 голосов
/ 18 мая 2019

Я просто хочу лично поблагодарить всех, кто пытался помочь мне с моей проблемой. Однако мне удалось найти решение. Вместо использования функции «os.removedirs». Я использовал функцию с именем 'shutil.rmtree (directoryPath)', которая удаляла введенный каталог без предупреждений. Хотя я не смог бы сделать это без помощи, которую я получил, поэтому спасибо всем, кто принял участие!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...