你应该使用 \n 而不是 /r/n -> 'y\npassword'
由于你的问题不清楚,我假设你有一个行为有点像这个 python 脚本的程序,我们称之为 script1.py:
import getpass
import sys
firstanswer=raw_input("Do you wish to continue?")
if firstanswer!="y":
sys.exit(0) #leave program
secondanswer=raw_input("Enter your secret password:\n")
#secondanswer=getpass.getpass("Enter your secret password:\n")
print "Password was entered successfully"
#do useful stuff here...
print "I should not print it out, but what the heck: "+secondanswer
它要求确认(“y”),然后要求您输入密码。之后它会做一些“有用的事情”,最后打印密码然后退出
现在要让第二个脚本 script2.py 运行第一个程序,它必须看起来像这样:
import subprocess
cmd_suppression="python ./testscript.py"
process=subprocess.Popen(cmd_suppression,shell=True\
,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
response=process.communicate("y\npassword")
print response[0]
script2.py 的输出:
$ python ./script2.py
Do you wish to continue?Enter your secret password:
Password was entered successfully
I should not print it out, but what the heck: password
如果程序使用特殊方法以安全的方式获取密码,即如果它使用我刚刚在 script1.py 中注释掉的行,则很可能会出现问题
secondanswer=getpass.getpass("Enter your secret password:\n")
这个案例告诉你,通过脚本传递密码可能不是一个好主意。
还要记住,使用 shell=True 选项调用 subprocess.Popen 通常也是一个坏主意。使用 shell=False 并将命令作为参数列表提供:
cmd_suppression=["python","./testscript2.py"]
process=subprocess.Popen(cmd_suppression,shell=False,\
stdin=subprocess.PIPE,stdout=subprocess.PIPE)
Subprocess 文档中提到了十几次