我想调用一个脚本,将字符串的内容传递给它的stdin并检索它的标准输出。
我不想触及真正的文件系统,所以我无法为它创建真正的临时文件。
使用subprocess.check_output
我可以得到脚本写的任何内容;我怎样才能将输入字符串输入到stdin中?
subprocess.check_output([script_name,"-"],stdin="this is some input")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1043, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'str' object has no attribute 'fileno'
答案 0 :(得分:32)
使用Popen.communicate
代替subprocess.check_output
。
from subprocess import Popen, PIPE
p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate("this is some input")
答案 1 :(得分:20)
在Python 3.4及更新版本中,您可以使用 input 关键字参数在使用subprocess.check_output()
时通过STDIN发送输入
引自the standard library documentation for subprocess.check_output()
:
输入参数传递给
Popen.communicate()
,因此传递给。{} subprocess的标准输入。如果使用它必须是字节序列,或者是字符串ifuniversal_newlines=True
。使用时,内部Popen
对象是 使用stdin=PIPE
自动创建, stdin 参数可能不会 也可以使用。
示例:
>>> subprocess.check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
>>>
>>> # To send and receive strings instead of bytes,
>>> # pass in universal_newlines=True
>>> subprocess.check_output(["sed", "-e", "s/foo/bar/"],
... universal_newlines=True,
... input="when in the course of fooman events\n")
'when in the course of barman events\n'
答案 2 :(得分:6)
这是带有输入的python 2.7的check_output backported版本。
.nav-flex {
display: flex;
list-style-type: none;
padding: 0;
background-color: #58575f;
li {
justify-content: center;
a {
align-self: center;
color: white;
font-weight: 300;
font-family: 'Open Sans', sans-serif;
letter-spacing: .4px;
}
}
@media (max-width: 760px) {
padding-top: 0;
flex-wrap: nowrap;
-webkit-flex-wrap: nowrap;
flex-direction: column;
-webkit-flex-direction: column;
background-color: #f6f6f6;
}
}
.nav-link-flex {
display: flex;
padding: 0 12.5px;
position: relative;
@media (max-width: 760px) {
width: 90%;
background-color: #494949;
border-radius: 20px;
margin-bottom: 10px;
margin-left: auto;
margin-right: auto;
font-size: 22px;
padding: 10px;
}
&:hover {
background-color: white;
a {
color: black;
text-decoration: none;
&+ div {
display: block;
}
}
}
a {
&+ div {
border-radius: 0 0 2px 2px;
box-shadow: 0 3px 1px rgba(0,0,0,.05);
display: none;
font-size: 1rem;
position: absolute;
width: 195px;
}
}
}
.nav-brand-flex {
margin-right: auto;
display: flex;
padding: 5px 0;
a {
display: flex;
img {
height: 35px;
align-self: center;
}
}
@media (max-width: 760px) {
margin: 0;
background-color: #494949;
width: 100%;
border-radius: 0;
font-size: 36px;
padding: 10px 0;
margin-bottom: 10px;
}
}