Python subprocess: how to send a password (rclone

2019-08-24 23:15发布

问题:

I would like to use rlcone inside python. If I don't encrypt my rclone config with a password, then I can simply do this:

import subprocess 
process = subprocess.Popen(["rclone", "listremotes"], shell=True, stdin=subprocess.PIPE)
output = process.communicate()
print(output)

But I want to protect my Rclone config with a password, so I need a way to send it to rclone. I followed this answer but I get the error Failed to read password: The handle is invalid:

import subprocess 
psw= input("enter psw")
psw_byte= str.encode(psw+'\n')
process = subprocess.Popen(["rclone", "listremotes"], shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.stdin.write(psw_byte)
process.stdin.flush()
output = process.communicate()
print(output)

回答1:

I recommend you use the RCLONE_CONFIG_PASS environment variable to pass the config password into rclone. See the section in the docs about configuration encryption.

Eg

os.environ("RCLONE_CONFIG_PASS") = "mypassword"

Unix programs reading passwords tend not to be scriptable like this unless you assign a tty.

That is quite a lot of trouble though, so I recommend just setting the environment variable instead.

PS If you want to just set the enviroment for the subprocess you can do it like this: Python subprocess/Popen with a modified environment

PPS I'm the author of rclone :-)



回答2:

One way around is to use subprocess.call() and to call a .cmd into which you store the cmd command:

in python:

import subprocess
cmd_path = "C:\Users\user\Desktop\rclone_command.cmd"
subprocess.call([cmd_path]) 

in rclone_command.cmd (after rclone is done sync, you can start another python script cf start ex to parse the log):

rclone sync  "C:\my path" "remote":"folder" --log-file "C:\Users\user\Desktop\log.log"  --log-level INFO --delete-after   --exclude "desktop.ini" 

start "" "C:\Users\user\Desktop\some other script.py"