我正在尝试使用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,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安装程序。我在这里完全迷路了。

解决方法

对于单个目录:

os.mkdir(...)

对于嵌套目录:

os.makedirs(...)

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

os.path.exists(...)