为Popen.communicate()传递整数输入参数 [英] Pass integer input argument for Popen.communicate()
问题描述
我对python来说还很陌生,现在我迷上了某些东西.我正在使用python 2.7. 我试图在我为其编写了python脚本的shell中自动执行命令.我必须向要使用Popen.communicate(input ='2')的外壳输入一个整数值.尽管传递了输入,但它以字符串形式传递,并且子进程需要将其作为数字值传递.当我尝试将其作为数字值(如Popen.communicate(input = 2))传递时,它将引发以下错误:
I am pretty new to python and I am stuck with something now. I am using python 2.7. I am trying to automate a command in shell for which I wrote a python script. I have to input an integer value to the shell for which I am using Popen.communicate(input='2'). Though input is passed, it is passed as a string and the subprocess needs it as a numeric value. When I try to pass it as a numberic value like Popen.communicate(input=2) it throws the following error :
TypeError:"int"对象没有属性" __ getitem __ "
那么有什么方法可以将输入作为数值发送?
So is there any way to send the input as a numeric value ??
这是我使用的代码:
import sys
from subprocess import Popen, PIPE, STDOUT
cmd = ["sudo", "./sbt", "project java-examples", "run"]
proc = Popen(cmd, bufsize=4096, shell=False, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
string = proc.communicate(input='2')
print string[0]
proc.stdin.close()
抱歉,我最初没有提到这一点. 我的Java应用程序有多个主类,因此编译器会询问要执行哪个类,并且每次都需要输入相同的数字,这就是我试图使其自动化的原因.当我传递字符串值时,它将引发numberformatexception.
Edit : Sorry that I didn't mentioned this at the first place. My java application has multiple main classes hence the compiler ask which class to be executed, and I need to enter the same number every time,which is why I am trying to automate it. When I am passing a string value it throws numberformatexception.
推荐答案
最后,我找到了解决方案. 很好的解决方案很简单
Finally I found the solution for this. Well the solution to this was pretty simple
当我改变
string = proc.communicate(input ='2')
string = proc.communicate(input='2')
到
string = proc.communicate(input ='2 \ n')
string = proc.communicate(input='2\n')
工作正常.
这篇关于为Popen.communicate()传递整数输入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!