读入文件夹路径和整数值的命令行参数

Read in command line arguments for folder paths and integer values

本计划的目标是:

  1. 接收 2 个文件夹路径
  2. 取 1 个整数值
  3. 验证两个文件夹都在目录中并且整数值是一个 int
  4. 将指定数量的文件从源文件夹移动到目标文件夹。例如,如果源文件夹包含 8 个文件,我想将最后 4 个文件移动到目标文件夹。
  5. 在命令行中: python main.py path1 path2 4

我正处于使用命令行参数而不是默认值占位符(文件夹路径和分配给变量的整数值)和通过控制台 运行 的测试阶段。

我的问题是:

  1. 当 path1、path2 和 int 都存在且值正确时,一切都按预期工作
  2. 如果整数不是整数(例如,python main.py path1 path2 string)程序崩溃并给出错误。
  3. 如果程序读取 CLI arg 不是 int (num = int(sys.argv[3])) 我想将该值默认为 10 ,但是程序好像没有这样做?

错误

空白 = 屏蔽个人信息
python main.py 路径 1 路径 2 L

Traceback (most recent call last):
  File "C:\Users\blank\blank\blank\main.py", line 71, in <module>
    main()
  File "C:\Users\blank\blank\blank\main.py", line 66, in main
    read_args()
  File "C:\Users\blank\blank\blank\main.py", line 29, in read_args
    num = int(sys.argv[3])
ValueError: invalid literal for int() with base 10: 'L'

主要

import os, sys, shutil, time

def main():
    read_args()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        exit()

代码

def validate_folder(folder):
    """Validates folders in working directory"""
    try:
        isDir = os.path.isdir(folder)
        return isDir
    except Exception as e:
        print(e)
        return None

def validate_number(number1):
    """Validates third argument is an integer value"""
    try:
        int(number1)
        return True
    except ValueError:
        return False

def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = int(sys.argv[3])

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)
    kept_files = validate_number(num)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    if main_folder is True and archive_folder is True and kept_files is False:
        num = 10
        sortFiles_and_moveFiles(source_folder, destination_folder, num)
    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        sortFiles_and_moveFiles(source_folder, destination_folder, num)


def sortFiles_and_moveFiles(path1, path2, n_files):
    source_folder = path1
    destination_folder = path2
    """Get list of all files only in the given directory"""
    list_of_files = filter(lambda x: os.path.isfile(os.path.join(source_folder, x)), os.listdir(source_folder))

    """Sort list of files based on last modification time in descending order"""
    list_of_files = sorted(list_of_files, key=lambda x: os.path.getmtime(os.path.join(source_folder, x)))

    """Iterate over sorted list of files and print file path, along with last modification time of file"""
    for file_name in list_of_files:
        file_path = os.path.join(source_folder, file_name)
        timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S', time.gmtime(os.path.getmtime(file_path)))
        print(timestamp_str, ' -->', file_name)
    print("Designated files have been moved")
    
    """Move designated number of files to archive folder using slice notation."""
    for file_name in list_of_files[n_files:]:
        shutil.move(os.path.join(source_folder, file_name), destination_folder)

有内置函数 str.isdigit() returns True if string could be cast to int else False。您的一些 if 检查也可以缩短

if main_folder is True and archive_folder is True and kept_files is False:

可以替换为简单

elif kept_files is False:

但整个方法仍然可以修改如下

def read_args():
    """Read CLI arguments"""
    source_folder = sys.argv[1]
    destination_folder = sys.argv[2]
    num = sys.argv[3]

    """Get main folder and archive folder and validate they are in the directory"""
    main_folder = validate_folder(source_folder)
    archive_folder = validate_folder(destination_folder)

    """If any of the inputs is not valid return None proceed with conditional checks"""
    if main_folder is False or archive_folder is False:
        print("Folders cannot be found")
    elif not num.isdigit():
        num = 10
        
    else:
        """If both folders are valid in the working directory pass parameters to sortFiles_and_moveFiles()"""
        num = int(num)
    sortFiles_and_moveFiles(source_folder, destination_folder, num)