Python code to send command through command line

2019-06-04 20:49发布

问题:

final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\""  + "  /p " + str
os.system(final)

I am trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e

it asks ARE YOU SURE(Y/N) and the user needs to enter "Y" or "N"

Is there any way to use python to send the user input "Y" along with the above code?

    pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
    pro.communicate(bytes("Y\r\n",'utf-8'))

I have added the following code . The program exits without setting the permission.

http://jimmyg.org/blog/2009/working-with-python-subprocess.html#writing-to-standard-input

回答1:

Try using the subprocess module

import subprocess
cmd = ["cacls",  "E:/" + list1[2], list1[3], "/p", str]

pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")


回答2:

As a smart programmer, use PBS

Then, the code is:

from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one

script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\""  + "  /p " + str).split())