Python script says The filename, directory name, or volume label syntax is incorrect

Hi so i’m trying to make a python script to do some automation to generate a file from some tools(can’t name them but the commands will give you an idea) and while I made a script that passes commands to cmd/terminal (cmd in mycase) using os.system like given below

os.system('"' + dc_dir + '" --scan "' + in_dir + '" --out "' + out_dir + '\'+ Project_name + '.csv' + '" --format CSV --enableExperimental')

and it returns "The filename, directory name, or volume label syntax is incorrect."

but when i print the exact same line and run it manually it works

print('"' + dc_dir + '" --scan "' + in_dir + '" --out "' + out_dir + '\'+ Project_name + '.csv' + '" --format CSV --enableExperimental')

this is the command printed

"C:SBOMdependency-check-6.2.2bindependency-check.bat" --scan "C:FinalScriptSource CodesSireous" --out "C:SBOMSiriusProgrammer_2_0.csv" --format CSV --enableExperimental

please help me out with this if possible.

Answer

Let’s try to localize the problem. To do so we need to re-organize your code a bit:

  1. It is not how we concatenate strings nowadays. That’s the way:

    dc_dir = 'C:\SBOM\dependency-check-6.2.2\bin\dependency-check.bat'
    in_dir = 'C:\FinalScript\Source Codes\'
    out_dir = 'C:\SBOM\'
    Project_name = 'SiriusProgrammer_2_0'
    
    f'{dc_dir} --scan {in_dir}{Project_name} --out {out_dir}{Project_name}.csv --format CSV --enableExperimental'
    
  2. It is better to use libraries dedicated to specific task. pathlib will help you to avoid escape clattering.

    from pathlib import Path
    
    project_name = 'SiriusProgrammer_2_0'
    project_dir = Path('C', 'SBOM')
    
    dependency_check_bat = project_dir.joinpath('dependency-check-6.2.2', 'bin', 'dependency-check.bat')
    source_code_dir = Path('C', 'FinalScript', 'Source Codes', project_name)
    
    f'{dependency_check_bat.as_posix()} --scan {source_code_dir.as_posix()} --out {project_dir.joinpath(project_name).as_posix()}.csv --format CSV --enableExperimental'
    
  3. As for the main problem, I suggest using subprocess, which is handy if you want to pass variables to the script:

    import subprocess
    
    process_run = subprocess.Popen([dependency_check_bat.as_posix(),
                                    '--scan',
                                    source_code_dir.as_posix(),
                                    '--out',
                                    f'{project_dir.joinpath(project_name).as_posix()}.csv',
                                    '--format CSV',
                                    '--enableExperimental'],
                                    stdout=subprocess.PIPE)
    
    terminal_output = process_run.communicate()[0]
    print(terminal_output)
    

Let’s do this and see what terminal will return to us.