python read stdinstdin 为pipe什么意思

3130人阅读
Windows上Python读取stdin出错(金庆的专栏)一段简单的代码,读取stdin, 替换输出到stdout:#!/usr/bin/env pythonimport os, sysinput_file = sys.stdinoutput_file = sys.stdoutfor s in input_file:&&& output_file.write(s.replace(&abc&, &def&))代码改自CookBook的&& &Recipe 2.3. Searching and Replacing Text in a File在Linux上运行正常:$ cat input.txt | ./replace.py&但是在Windows的Dos窗口运行会报错:& type input.txt | replace.pyTraceback...&&& for s in input_file:IOError: [Errno 9] Bad file descriptor如果用python调用就正常:& type input.txt | python replace.py原因是cmd.exe通过后缀关联运行py文件存在问题。详见:Bad pipe filedescriptor when reading from stdin in python/questions/1057638/bad-pipe-filedescriptor-when-reading-from-stdin-in-pythonIt seems that stdin/stdout redirect does not work when starting from a file association. This is not specific to python, but a problem caused by win32 cmd.exe.
版权声明:本文为博主原创文章,未经博主允许不得转载。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:678769次
积分:10639
积分:10639
排名:第631名
原创:313篇
转载:48篇
译文:19篇
评论:372条
(2)(1)(1)(4)(3)(4)(4)(4)(3)(3)(2)(3)(1)(4)(1)(4)(5)(5)(5)(2)(2)(2)(2)(1)(2)(1)(1)(1)(3)(2)(1)(3)(2)(3)(2)(2)(3)(2)(2)(3)(2)(3)(2)(1)(2)(2)(3)(2)(3)(1)(3)(3)(5)(4)(4)(2)(2)(4)(3)(2)(4)(1)(3)(4)(2)(5)(1)(7)(4)(1)(3)(4)(3)(5)(6)(7)(6)(5)(7)(5)(5)(6)(9)(6)(6)(9)(7)(5)(5)(4)(2)(8)(7)(9)(14)(16)(16)(16)&&&&&&&&&&&&&&&&&&
posts - 334,comments - 40,trackbacks - 2
cmd = "e:\\dmin\\AdminD.exe online"
&&&&&&& ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
&&&&&&& ps.stdin.write("file=烂烂烂服务器.role\n") #注意加"\n"
&&&&&&& ps.stdin.write("exit\n")
&&&&&&& data = ps.stdout.read()
&&&&&&& #data = ps.communicate("file=烂烂烂服务器.role"
阅读(...) 评论()for line in sys.stdin 在网上查资料的时候还发现有人反馈Python使用for line in sys.stdin的一个bug :Issue1633941,就是需要输入两次CRTL+D程序才会退出。Ralph Corderoy指出这 …
Java中执行Python脚本中sys.stdin.readline()的问题 目前我正在做一个用Java调用Python脚本的程序,Java程序将获取Python的输出stdout和stderr,并通过stdin向 python发送命令。我写了一个简单的python demo程序,如下:
python stdinpython stdin_python command_sys.stdout_python基础教程_sys.stdin_python reload_python3.3.3 reload ... python中的模块 长:439高:222大小:16;类型:JPG
Reading from stdin Reading from stdin Python Python ... & probably both your C- and your python scripts use buffered output. So & the C-program will not print line-by-line but rather en ...
python read from stdinNote on Python version: The following uses the syntax of Python 2.x. Some of the .... Note that sys.stdin.read() will read from standard input till EOF. (which is ...
Python执行系统命令,os.system && os.popen ...1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 4 import subprocess 5 6 p =subprocess.Popen(' python C://plus.py ', shell=True, stdin=subprocess.PIPE, stdout …
python subprocess Popen python subprocess Popen,yi_yixinyiyi的网易博客 ,脚踏实地, 网易 新闻 LOFTER 邮箱 相册 ... 参数stdin,stdout,stderr分别表示程序的标准输入、输出、错误句柄.他们可以是 ...
stdin, stdout, stderr以及重定向 stdin, stdout, stderr以及重定向:stdin, stdout, stderr以及重定向 作者:Sam(甄峰) sam_ stdin, stdout,stderr ... @稻草鸟人:python interpreters ... 48 ...
python 脚本从屏幕输出读取数据sys.stdin 怎样可以每读取10 ...sys.stdin, 来源于Python Class file(object), 所以其方法或属性与file的类似,readlines方法只有一个参数[size],用来控制数据的行大小,所以readlines并没有控制行 ...
Python的sys.stdout、sys.stdin重定向 Python的sys.stdout、sys.stdin重定向 ,深度IT技术,移动开发,Web前端,企业架构,编程语言,互联网,数据库,系统运维,云计算,研发管理I'm trying to do some of the
challenges, but they all require the input to be taken from stdin. How do I get that in Python?
8,690105895
4,33881915
You could use the
import fileinput
for line in fileinput.input():
will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.
There's a few ways to do it.
is a file-like object on which you can call functions read or readlines if you want to read everything or you want to read everything and split it by newline automatically.
If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.
If you actually just want to read command-line options, you can access them via the
You will probably find
to be a useful reference as well.
116k18258318
import sys
for line in sys.stdin:
print line
100k26191226
Here's from :
import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."
On Unix, you could test it by doing something like:
% cat countlines.py | python countlines.py
Counted 3 lines.
On Windows or DOS, you'd do:
C:\& type countlines.py | python countlines.py
Counted 3 lines.
Python also has built-in functions input() and raw_input(). See the Python documentation under .
For example,
name = raw_input("Enter your name: ")
# Python 2.x
name = input("Enter your name: ")
# Python 3
23.3k45560
64.9k216883
The answer proposed by others:
for line in sys.stdin:
print line
is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input.
This means that tail -f error_log | myscript.py will not process lines as expected.
The correct script for such a use case would be:
line = sys.stdin.readline()
except KeyboardInterrupt:
if not line:
print line
From the comments it has been cleared that on python 2 only there might be buffering involved, so that you end up waiting for the buffer to fill or EOF before the print call is issued.
This will echo standard input to standard output:
import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
Building on all the anwers using sys.stdin, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise:
import sys
f = open(sys.argv[1]) if len(sys.argv) & 1 else sys.stdin
for line in f:
Do your stuff
and use it as either
$ python do-my-stuff.py infile.txt
$ cat infile.txt | python do-my-stuff.py
$ python do-my-stuff.py & infile.txt
That would make your Python script behave like many GNU/Unix programs such as cat, grep and sed.
6,15053274
2,95821636
You can read from stdin and then store inputs into "data" as follows:
for line in sys.stdin:
data += line
import sys
print sys.stdin.read().upper()
and check it with:
$ echo "Hello World" | python myFile.py
input([prompt]) is equivalent to eval(raw_input(prompt)) and is available since python 2.6
As it is unsafe (because of eval), raw_input should be preferred for critical applications.
I had some issues when getting this to work for reading over sockets piped to it. When the socket got closed it started returning empty string in an active loop. So this is my solution to it (which I only tested in linux, but hope it works in all other systems)
import sys, os
sep=os.linesep
while sep == os.linesep:
data = sys.stdin.readline()
sep = data[-len(os.linesep):]
print '& "%s"' % data.strip()
So if you start listening on a socket it will work properly (e.g. in bash):
while :; do nc -l 12345 | python test. done
And you can call it with telnet or just point a browser to localhost:12345
Maybe this is useful for someone.
#! /usr/bin/env python
#Given a secuencia of integer numbers through stdin
#returns its sum through stdout
import sys
for line in sys.stdin:
regexp = re.compile("-?[0-9]+")
numeros=[int(i) for i in regexp.findall(line)]
for j in range(0,len(numeros)):
num = num + numeros[j]
protected by
Thank you for your interest in this question.
Because it has attracted low-quality answers, posting an answer now requires 10
on this site.
Would you like to answer one of these
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 python read stdin 的文章

 

随机推荐