问题
I've used successfully subprocess.check_output to call plenty of windows programs.
Yet, I'm troubled at calling icacls.
By cmd, this works:cmd>icacls "C:\my folder" /GRANT *S-1-1-0:F
I've tried:subprocess.check_output(['C:\\Windows\\System32\\icacls.exe','"C:\\my folder"','/GRANT *S-1-1-0:F'],shell=True,stderr=subprocess.STDOUT)
but return code is 123 (according to micrsoft, invalid file name).
I've also tried (which also works from cmd)subprocess.check_output(['C:\\Windows\\System32\\icacls.exe','"C:/my folder"','/GRANT *S-1-1-0:F'],shell=True,stderr=subprocess.STDOUT)
but return code is also 123.
Any idea?
回答1:
don't overquote your arguments, or they are passed literally. Let check_output
handle the quoting when needed. Best way using a list of arguments:
subprocess.check_output(['icacls.exe',r'C:\my folder','/GRANT','*S-1-1-0:F'],stderr=subprocess.STDOUT)
(note that I removed shell=True
and the path to the command, and used raw prefix to avoid doubling the backslashes for the folder argument)
回答2:
@Jean-François Fabre gave me the clue:
Quoting my target argument made sense, since it has blanks and, so, quoting is required when calling from cmd. However, it seems python will over-quote.
Thank you all guys for your help!!!
回答3:
On Windows, you're probably better off providing a string for the command line rather than a sequence, particularly if you already know exactly what the command line you want looks like. Passing a string tells Python that you know what you're doing, and it shouldn't try to add quotes or otherwise modify the command:
subprocess.check_output(
r'C:\Windows\System32\icacls.exe "C:\my folder" /GRANT *S-1-1-0:F',
stderr=subprocess.STDOUT)
来源:https://stackoverflow.com/questions/45421302/calling-windows-icacls-from-python