首页 > 解决方案 > 我正在尝试使用 os.mkdir 创建一个目录

问题描述

import pathlib
import subprocess
import argparse
import os
from _datetime import datetime


def get_unique_run_id():

    if os.environ.get("BUILD_NUMBER"):
        unique_run_id = os.environ.get("BUILD_NUMBER")
    elif os.environ.get("CUSTOM_BUILD_NUMBER"):
        unique_run_id = os.environ.get("CUSTOM_BUILD_NUMBER")
    else:
        unique_run_id = datetime.now().strftime('%Y%M%D%H%M%S')

    os.environ['UNIQUE_RUN_ID'] = unique_run_id

    return unique_run_id


def create_output_directory(prefix='results_'):

    global run_id
    if not run_id:
        raise Exception("Variable 'run_id' is not set. Unable to create output directory")

    curr_file_path = pathlib.Path(__file__).parent.absolute()
    dir_to_create = os.path.join(curr_file_path, prefix + str(run_id))
    os.mkdir(dir_to_create)

    print(f"Created output directory: {dir_to_create}")

    return dir_to_create


if __name__ == "__main__":
    run_id = get_unique_run_id()
    output_dir = create_output_directory()
    json_out_dir = os.path.join(output_dir, 'json_report_out.json')
    junit_out_dir = os.path.join(output_dir, 'junit_report_out')
    # import pdb; pdb.set_trace()
    parser = argparse.ArgumentParser()
    parser.add_argument('--test_directory', required=False, help='Specify the location of the test file')
    parser.add_argument('--behave_options', type=str, required=False, help='String of behave options')
    args = parser.parse_args()
    test_directory = '' if not args.test_directory else args.test_directory
    behave_options = '' if not args.behave_options else args.behave_options
    command = f'behave -k--no-capture -f json.pretty -o {json_out_dir} ' \
              f'--junit --junit-directory {junit_out_dir}' \
              f'{behave_options} ' \
              f'{test_directory}'
    print(f"Running command : {command}")
    rs = subprocess.run(command, shell=True)

当我尝试运行此程序时,我收到如下错误:FileNotFoundError: [WinError 3] 系统找不到指定的路径:'E:\Projects\results_20204710/11/20194751'。请帮助我找到解决方案。

以为可能是安装程序错误。所以尝试了 32 位和 64 位 python 安装程序。我完全迷失在这里。

标签: pythonfilenotfoundexception

解决方案


对于单个目录:

os.mkdir(...)

对于嵌套目录:

os.makedirs(...)

您还可以检查目录是否存在:

os.path.exists(...)

推荐阅读