Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run shell from python to open a file

Trying to open a file using shell :

os.system("G:\Folder\2. Cntry\ACCD.accdb")

throw the following error :

'G:\Folder.' is not recognized as an internal or external command,

operable program or batch file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However when I paste "G:\Folder\2. Cntry\ACCD.accdb" into cmd prompt, it does open the file.

It seems that \2 is read as a .

but using :

os.system(r"G:\Folder\2. Cntry\ACCD.accdb")

returns :

'G:\Folder\2.' is not recognized as an internal or external command,
operable program or batch file.

How can I do ?

>Solution :

As the backslash is an escape character in Python, you could:

  • Use an raw string: r"G:\Folder\2. Cntry\ACCD.accdb"
  • Use forward slashes: "G://Folder//2. Cntry//ACCD.accdb"
  • Escape the backslashes: "G:\\Folder\\2. Cntry\\ACCD.accdb"

Which works for any subprocess function.

Using os.system you need to pass the path additionally surrounded with single quotes:

import os
import subprocess

paths = (
    [r"C:\Temp\2. Cntry\executer.exe", r'"C:\Temp\2. Cntry\executer.exe"'],
    ["C://Temp//2. Cntry//executer.exe", '"C://Temp//2. Cntry//executer.exe"'],
    ["C:\\Temp\\2. Cntry\\executer.exe", '"C://Temp//2. Cntry//executer.exe"'],
)

for p1, p2 in paths:
    subprocess.call(p1)
    os.system(p2)

Out:

Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done
Arguments passed:
C:\Temp\2. Cntry\executer.exe
done
Arguments passed:
C://Temp//2. Cntry//executer.exe
done
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading