Home > Software engineering >  What is the correct synthax for os.system(" commande"" ") in python on windows
What is the correct synthax for os.system(" commande"" ") in python on windows

Time:08-04

I'm trying to execute a cmd command in my python script. But ther is some ' "" ' in the cmd commande and im using the os.system python library whitch break the ' "" ' of the python commande.

def open_HashMyFiles():
 os.system(".\HashMyFiles.exe /MD5 1 /SHA1 1 /SHA256 1  /CRC32 0 /SHA512 0 /SHA384 0 /SaveDirect /folder "C:\Users\PycharmProjects\pythonProject\WinHASH_py" /scomma "oktier.csv"")

What syntax shoud I use to make this work ?

I tried : os.system(', os.system([, os.system(`, os.system({.

CodePudding user response:

You can use single quotes arround and make your string a raw-string as you got unescaped backslashes in your command:

def open_HashMyFiles():
 os.system(r'.\HashMyFiles.exe /MD5 1 /SHA1 1 /SHA256 1  /CRC32 0 /SHA512 0 /SHA384 0 /SaveDirect /folder "C:\Users\PycharmProjects\pythonProject\WinHASH_py" /scomma "oktier.csv"')

CodePudding user response:

You need to use the backslash escape character \. If you need a " in your string and you want to use " as the string delimiter, you'll need to "escape" your inner quotation mark.

# Don't use this code, see below for a better version of this
def open_HashMyFiles():
 os.system(".\HashMyFiles.exe /MD5 1 /SHA1 1 /SHA256 1  /CRC32 0 /SHA512 0 /SHA384 0 /SaveDirect /folder \"C:\Users\PycharmProjects\pythonProject\WinHASH_py\" /scomma \"oktier.csv\"")

You need to be careful with this escape character in your file paths - if one of your folders starts with n and you put a \ to symbolize accessing the folder, it will combine into a \n and become a new line! Usually for these cases we use the r string flag to prevent unnecessary escape sequences from working.

def open_HashMyFiles():
 os.system(r".\HashMyFiles.exe /MD5 1 /SHA1 1 /SHA256 1  /CRC32 0 /SHA512 0 /SHA384 0 /SaveDirect /folder \"C:\Users\PycharmProjects\pythonProject\WinHASH_py\" /scomma \"oktier.csv\"")

With the r flag, the only escape sequences that will work are to escape the quotation characters. Useful if you use \ in your string but don't need newlines.

But possibly the easiest way is to use single quotes if you aren't strict about what string delimiter is used. The r flag works on this too.

def open_HashMyFiles():
 os.system(r'.\HashMyFiles.exe /MD5 1 /SHA1 1 /SHA256 1  /CRC32 0 /SHA512 0 /SHA384 0 /SaveDirect /folder "C:\Users\PycharmProjects\pythonProject\WinHASH_py" /scomma "oktier.csv"')
  • Related