stdin 未保存到文件中

问题描述 投票:0回答:1

我试图更好地理解 stdin 的工作原理以及如何在 Python 中具体使用它。

我正在尝试将从标准输入接收到的所有内容保存到文件中。该文件应该有两行

  • 第一行应该是字符串的字母数
  • 第二行应该是字符串本身
rawLength = sys.stdin.buffer.read(12)
file = open("my_file.txt", "w") 
file.write(len(rawLength) + "\n" + rawLength)       #file.write(rawLength)  <== Does not work either
file.close

文件确实已创建,但没有任何反应。它是空的,并且在python程序退出后仍然为空。

我尝试了这个,果然控制台确实打印了它,如图所示这里

import time

rawLength = sys.stdin.buffer.read(12)    #save std to var
time.sleep(3)                            #because console window closes too fast
print(len(rawLength))
print(rawLength)
time.sleep(44)

这个练习的目的是增加我对std的理解,这样我就可以解决我昨天问的这个问题

任何帮助将不胜感激!

python stdin
1个回答
0
投票

你的基本理念很好,但细节上有缺陷。请注意这个轻微的重写,使用

print
而不是
file.write
。您的 write 调用无法工作,因为您混合了一个整数、一个 Unicode 字符串和一个字节字符串。这有效:

import sys
rawLength = sys.stdin.buffer.read(12)
file = open("my_file.txt", "w") 
print(len(rawLength), file=file)
print(rawLength.decode(), file=file)
file.close()

输出:

timr@Tims-NUC:~/src$ python x.py
asdfhlaksjdf
timr@Tims-NUC:~/src$ cat my_file.txt 
12
asdfhlaksjdf
timr@Tims-NUC:~/src$

作为一般规则,这不是在 Python 程序中使用

stdin
的方式。
stdin
往往是文本,因此我们使用
sys.stdin.readline
、或
for line in sys.stdin:
、或
fileinput
模块。

© www.soinside.com 2019 - 2024. All rights reserved.