我正在执行一个脚本,它一个接一个地提示输入2个值。我想要传递来自脚本本身的值,因为我想自动化这一点。
使用子进程模块,我可以轻松地传递一个值:
suppression_output = subprocess.Popen(cmd_suppression, shell=True,
stdin= subprocess.PIPE,
stdout= subprocess.PIPE).communicate('y') [0]但是传递第二个值似乎不起作用。如果我这样做:
suppression_output = subprocess.Popen(cmd_suppression, shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE).communicate('y/r/npassword')[0]发布于 2014-03-18 09:23:17
应使用\n作为新行,而不是/r/n密码‘y\n ->’
由于你的问题不清楚,我假设你有一个程序,它的行为有点像这个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文档中被提到了十几次
发布于 2014-03-18 12:58:09
试试os.linesep
import os
from subprocess import Popen, PIPE
p = Popen(args, stdin=PIPE, stdout=PIPE)
output = p.communicate(os.linesep.join(['the first input', 'the 2nd']))[0]
rc = p.returncode在Python 3.4+中,您可以使用check_output()
import os
from subprocess import check_output
input_values = os.linesep.join(['the first input', 'the 2nd']).encode()
output = check_output(args, input=input_values)注意:子脚本可能会直接从终端请求密码,而不使用子进程的stdin/stdout。在这种情况下,您可能需要pexpect或pty模块。请参阅Q: Why not just use a pipe (popen())?
import os
from pexpect import run # $ pip install pexpect
nl = os.linesep
output, rc = run(command, events={'nodes.*:': 'y'+nl, 'password:': 'test123'+nl},
withexitstatus=1)https://stackoverflow.com/questions/22468215
复制相似问题