简体   繁体   English

我们如何在python脚本中自动进行用户交互

[英]How can we automate the user interaction in python script

When i execute the below command, it usually asks for the user input. 当我执行以下命令时,通常会要求用户输入。 How can we automate the user interaction in python script. 我们如何在python脚本中自动化用户交互。

os.system("openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095") os.system(“ openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095”)

Use subprocess.Popen to initiate the command and then communicate to simulate user interaction. 使用subprocess.Popen启动命令,然后进行communicate以模拟用户交互。

import subprocess

process = subprocess.Popen(['openssl', 'req', '-new', ...], 
                stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = process.communicate(input='input1\ninput2')

For that specific command, you should not need any automation tool to feed input to your script. 对于该特定命令,您不需要任何自动化工具即可将输入提供给脚本。 Piping a file to it should allow it to execute without user interaction (like Coldspeed said in his comment). 将文件放入文件中应使其无需用户交互即可执行(如Coldspeed在他的评论中所述)。

Most command line interfaces allow parametrized execution and most parameters you can either build into your script or read them from a config file somewhere. 大多数命令行界面都允许参数化执行,并且您可以将其内置到脚本中或从某个位置的配置文件中读取大多数参数。

For those command line tools that require "real" user interaction (ie you can't pipe the input, parametrize it or somehow build it into the command itself), I used the pexpect module with great success. 对于那些需要“真实”用户交互的命令行工具(即,您无法通过管道传递输入,对其进行参数化或以某种方式将其构建到命令本身中),我成功地使用了pexpect模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM