简体   繁体   English

如何在不打开的情况下使用 sys.stdin.readline()?

[英]How works with sys.stdin.readline() without open?

I'm trying to resolve an exercise in python. It has an platform with some pre-code part and I have to enter some code to complete.我正在尝试解决 python 中的练习。它有一个带有一些预代码部分的平台,我必须输入一些代码才能完成。 But usually, I like to try the code in VS Code as well, to understand a little more about the problem.但通常,我也喜欢尝试 VS Code 中的代码,以更多地了解问题。 In this case, the resolution was easy, but I couldn't understad the pre-coded part, in order to replicate.在这种情况下,分辨率很容易,但我无法理解预编码部分,以便复制。

import sys
import xml.etree.ElementTree as etree

def get_attr_number(node): 
    \# your code goes here
    return root

if __name__ == '__main__':
    sys.stdin.readline()
    xml = sys.stdin.read()
    tree = etree.ElementTree(etree.fromstring(xml))
    root = tree.getroot()
    print(get_attr_number(root))

In particular, I couldn't understand the stdin part.特别是,我无法理解 stdin 部分。 Usually i use it for read document, previously opened.通常我用它来阅读以前打开的文件。 How does it read the xml data from the input?它如何从输入中读取 xml 数据? This part is blocked, and works in the platform.这部分被屏蔽,并在平台中工作。 How can I replicate this process, providing data.我怎样才能复制这个过程,提供数据。 The input should be some xml code.输入应该是一些 xml 代码。

How can I input data from the terminal (Power Shell or terminal from VS Code) so it can process my data and I can execute the def function?我如何从终端(Power Shell 或 VS Code 的终端)输入数据,以便它可以处理我的数据并执行 def function?

In addition to Barmars precise answer some vsCode idea:除了 Barmars 精确回答一些 vsCode 想法:

  • Implement a dummy implementation:实施虚拟实施:
  • save yourprg.py保存你的prg.py
def get_attr_number(node): 
    # your code goes here
    print ("here is my solution")
    return root
    #enter code here
  • In vsCode open below a terminal window and type in:在 vsCode 中打开终端 window 并输入:
cat c:/tmp/file.xml | C:/Python/Python311/python.exe c:/tmp/yourprg.py

Folder tmp in only an example.文件夹 tmp 仅作为示例。 It should be your folder with yourprg.它应该是带有 yourprg 的文件夹。 (instead of C:/Python/Python311/python.exe you should type in your full path of your python.exe if not configured in your system or vsCode. (而不是 C:/Python/Python311/python.exe 如果您的系统或 vsCode 中没有配置,您应该输入 python.exe 的完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM