Python 你是如何阅读标准文本的?
我试图做一些挑战,但它们都需要从Python 你是如何阅读标准文本的?,python,stdin,Python,Stdin,我试图做一些挑战,但它们都需要从stdin获取输入。我如何在Python中获得它?以下是: 在Unix上,您可以通过执行以下操作进行测试: % cat countlines.py | python countlines.py Counted 3 lines. 在Windows或DOS上,您可以执行以下操作: C:\> type countlines.py | python countlines.py Counted 3 lines. 有几种方法可以做到这一点 是一个类似文件的对
stdin
获取输入。我如何在Python中获得它?以下是:
在Unix上,您可以通过执行以下操作进行测试:
% cat countlines.py | python countlines.py
Counted 3 lines.
在Windows或DOS上,您可以执行以下操作:
C:\> type countlines.py | python countlines.py
Counted 3 lines.
有几种方法可以做到这一点
- 是一个类似文件的对象,如果要读取所有内容或要读取所有内容并按换行自动拆分,则可以在其上调用函数
或read
。(您需要readlines
,才能使其正常工作。)导入系统
- 如果要提示用户输入,可以在Python2.X中使用,而只在Python3中使用
- 如果您实际上只想读取命令行选项,可以通过列表访问它们
行
将包含尾随的换行符;要删除它,请使用
请注意,这将在末尾包含一个换行符。要删除末尾的换行符,请使用@brittohaloran所说的
line.rstrip()
。Python还具有内置函数input()
和raw\u input()
。请参阅下的Python文档
比如说,
name = raw_input("Enter your name: ") # Python 2.x
或
其他人提出的答案是:
for line in sys.stdin:
print line
是非常简单和python的,但是必须注意,脚本将等到EOF之后才开始在输入行上迭代
def get_from_stdin():
lb = 0
stdin = ''
for line in sys.stdin:
if line == "\n":
lb += 1
if lb == 2:
break
else:
lb = 0
stdin += line
return stdin
这意味着tail-f error_log | myscript.py
将不会按预期处理行
这种用例的正确脚本是:
while 1:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if not line:
break
print line
# Filename e.g. cat.py
import sys
for line in sys.stdin:
print(line, end="")
更新从注释中可以看出,在python 2上可能只涉及缓冲区,因此在发出打印调用之前,您最终会等待缓冲区填充或EOF。这将把标准输入回送到标准输出:
import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
在使用
sys.stdin
的所有Anwer的基础上,如果至少存在一个参数,您还可以执行以下操作从参数文件中读取,否则返回到stdin:
import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
for line in f:
# Do your stuff
并将其用作
$ python do-my-stuff.py infile.txt
或
甚至
$ python do-my-stuff.py < infile.txt
$python do-my-stuff.py
这将使您的Python脚本的行为类似于许多GNU/Unix程序,如cat
、grep
和sed
尝试以下操作:
import sys
print sys.stdin.read().upper()
并通过以下方式进行检查:
$ echo "Hello World" | python myFile.py
您可以从stdin中读取数据,然后将输入存储到“数据”,如下所示:
data = ""
for line in sys.stdin:
data += line
我有一些问题,当让这项工作,通过插座读取管道到它。当套接字关闭时,它开始在活动循环中返回空字符串。这就是我的解决方案(我只在linux中测试过,但希望它能在所有其他系统中工作) 因此,如果您开始监听套接字,它将正常工作(例如在bash中):
您可以使用telnet调用它,或者只需将浏览器指向localhost:12345以下代码芯片将帮助您(它将所有stdin阻塞读取到
EOF
,并转换为一个字符串):
关于这一点:
用于系统标准中的行:
我只是为了一个非常大的文件在Python2.7上尝试了它(按照其他人的建议),我不推荐它,正是因为上面提到的原因(很长一段时间内没有发生任何事情)
我最终得到了一个更具python风格的解决方案(它适用于更大的文件):
然后我可以在本地运行脚本,如下所示:
python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
您如何阅读Python中的stdin?
我试图做一些代码高尔夫挑战,但它们都需要从stdin获取输入。我如何在Python中获得它
您可以使用:
- -类似对象的文件-调用
读取所有内容sys.stdin.read()
- -向它传递一个可选的提示以输出,它从stdin读取到第一个换行符,并将其剥离。您必须重复这样做才能获得更多的行,在输入的末尾,它会提高EOR。在Python 2中,这是
rawinput(prompt)
- -在Python 3中,内置函数
接受(表示操作系统IO资源的整数),0是open
的描述符。它返回一个类似文件的对象,如stdin
——这可能是你打高尔夫球的最佳选择。在Python2中,这是sys.stdin
-类似于open('/dev/stdin')。read()
,适用于Python 2和3,但不适用于Windows(甚至Cygwin)open(0)
- -在
sys.argv[1://code>中列出的所有文件中的行上返回迭代器,如果未给出,则返回stdin。使用类似于
'.join(fileinput.input())
sys
和fileinput
Quicksys.stdin
与Python 2和3、Windows和Unix兼容的示例
您只需要从sys.stdin
读取,例如,如果您将数据传输到stdin:
$ echo foo | python -c "import sys; print(sys.stdin.read())"
foo
我们可以看到,sys.stdin
处于默认文本模式:
导入系统
>>>sys.stdin
文件示例
假设您有一个文件,inputs.txt
,我们可以接受该文件并将其写回:
python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs.txt
使用我们已经看到的代码,我们可以检查是否创建了该文件:
$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs.txt
foo
bar
baz
$ python -m stdindemo2 < inputs.txt
foo
bar
baz
内置函数,input
(Python 2中的raw\u input
)
内置函数input
从标准输入读取一个换行符,该换行符被剥离(补充print
,默认情况下会添加一个换行符)。这种情况会一直发生,直到它获得EOF(文件结束),在该点它会引发eoferor
因此,您可以使用Python 3中的input
(或Python 2中的raw_input
)从stdin读取数据,因此我们创建了一个名为stdindemo.py的Python模块:
$ python -c "print('try:\n while True:\n print(input())\nexcept EOFError:\n pass')" > stdindemo.py
让我们一起
with open(sys.argv[1], 'r') as f:
for line in f:
python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
$ echo foo | python -c "import sys; print(sys.stdin.read())"
foo
python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs.txt
$ python -c "print('foo\nbar\nbaz')" > inputs.txt
$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs.txt
foo
bar
baz
read(size=-1, /) method of _io.TextIOWrapper instance
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.
$ python -c "print('try:\n while True:\n print(input())\nexcept EOFError:\n pass')" > stdindemo.py
$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < stdindemo.py
try:
while True:
print(input())
except EOFError:
pass
$ cat inputs.txt | python -m stdindemo
foo
bar
baz
$ python -m stdindemo < inputs.txt
foo
bar
baz
$ python stdindemo.py < inputs.txt
foo
bar
baz
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
$ python -c "print('import sys\nfor line in sys.stdin:\n sys.stdout.write(line)')" > stdindemo2.py
$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < stdindemo2.py
import sys
for line in sys.stdin:
sys.stdout.write(line)
$ python -m stdindemo2 < inputs.txt
foo
bar
baz
$ python -c "import sys; sys.stdout.write(sys.stdin.read())" < inputs.txt
foo
bar
baz
$ python -c "open(1,'w').write(open(0).read())" < inputs.txt
baz
bar
foo
$ python -c "from io import open; open(1,'w').write(open(0).read())" < inputs.txt
foo
bar
baz
''.join(sys.stdin)
sys.stdin.read()
import fileinput
for line in fileinput.input():
pass
import sys
for line in sys.stdin:
pass
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
python -c "import sys; set(map(sys.stdout.write,sys.stdin))"
import sys
for line in sys.stdin:
print(line)
import sys
import select
# select(files to read from, files to write to, magic, timeout)
# timeout=0.0 is essential b/c we want to know the asnwer right away
if select.select([sys.stdin], [], [], 0.0)[0]:
help_file_fragment = sys.stdin.read()
else:
print("No data passed to stdin", file=sys.stderr)
sys.exit(2)
#!/usr/bin/python
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('infile',
default=sys.stdin,
type=argparse.FileType('r'),
nargs='?')
args = parser.parse_args()
data = args.infile.read()
echo 'foo bar' | ./above-script.py
./above-script.py <<< 'foo bar'
echo 'foo bar' > my-file.data
./above-script.py my-file.data
echo 'foo bar' | ./above-script.py -
# Filename e.g. cat.py
import sys
for line in sys.stdin:
print(line, end="")
echo Hello | ./cat.py
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
def get_from_stdin():
lb = 0
stdin = ''
for line in sys.stdin:
if line == "\n":
lb += 1
if lb == 2:
break
else:
lb = 0
stdin += line
return stdin