1

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. But usually, I like to try the code in VS Code as well, to understand a little more about the problem. 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. Usually i use it for read document, previously opened. How does it read the xml data from the input? This part is blocked, and works in the platform. How can I replicate this process, providing data. The input should be some xml code.

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?

Pedro Lobo
  • 11
  • 1
  • 2
    `sys.stdin`, `sys.stdout`, and `sys.stderr` are opened automatically when the script starts. – Barmar Jan 27 '23 at 17:50
  • This script expects you to redirect input from the XML file: `python scriptname.py < file.xml` – Barmar Jan 27 '23 at 17:52
  • More than that, they're already pre-opened _before_ the script starts; Python inherits the file descriptors from its parent process, which is responsible for providing file descriptor 0 as stdin, 1 as stdout and 2 as stderr. – Charles Duffy Jan 27 '23 at 20:42

1 Answers1

0

In addition to Barmars precise answer some vsCode idea:

  • Implement a dummy implementation:
  • save yourprg.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:
cat c:/tmp/file.xml | C:/Python/Python311/python.exe c:/tmp/yourprg.py

Folder tmp in only an example. It should be your folder with 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.

ZoltanB
  • 79
  • 7
  • `cat file | ...` is better replaced with ` – Charles Duffy Jan 27 '23 at 20:43
  • Thanks, performace is important. Hopefully has "el Lobo" succeded solving the parsing exercise. – ZoltanB Jan 28 '23 at 16:41
  • Thanks all. The exercise itself was not the problem. Reasonably simple. I was trying to understand how the precode part works. So the file with the xml has to be open before, in the terminal command. Probably the first readline() will just get the first line and discard (in the format the input shall be provided, in the exercise, it has only the number of lines of xml code after that line) and than the xml = sys.stdin.read() will get the rest of the xml code. – Pedro Lobo Jan 30 '23 at 12:40