简体   繁体   中英

Reading lines from sys.stdin however ends up in a loop

I am trying to read lines from a text file however I get stuck trying to access the lines, or so I think.

import sys
import math
import re

CANVAS_HEIGHT = 500
CANVAS_WIDTH = 500

SVG_HEADER = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="%d" height="%d">\n'
SVG_BOUNDING_BOX = '<rect x="0" y="0" width="%d" height="%d" style="stroke:#000;fill:none" />\n'
SVG_LINE = '<line x1="%d" y1="%d" x2="%d" y2="%d" style="stroke:#000" />\n'
SVG_FOOTER = '</svg>'

print SVG_HEADER % (CANVAS_WIDTH, CANVAS_HEIGHT)
print SVG_BOUNDING_BOX % (CANVAS_WIDTH, CANVAS_HEIGHT)

try:
    line_number = 0
    for S in sys.stdin:
        line_number = line_number + 1

        L = S.split()
        try:
            x0 = float(L[1])
            y0 = float(L[2])
            x1 = float(L[3])
            x1 = float(L[4])
        except:
            sys.stderr.write('Error in line %d: %s\n' % (line_number, S))

    print SVG_LINE, x0, y0, x1, y1
except:
    sys.stderr.write('Cannot open: %s\n' % sys.argv[1])

print '%s\n' % (SVG_FOOTER)

In the terminal, I get stuck at the

for S in sys.stdin:

If you were wondering, the purpose of this code is to take lines and place them into svg format. All the sys.stderr.write is just specs from my prof.

The lines i am reading are just like

"line 0.0 1.0 2.0 3.0"

a bunch of times.

At this line:

for S in sys.stdin:

your program isn't stuck, it is waiting for input. Try typing:

line 0.0 1.0 2.0 3.0

followed by the EOF indicator (in UNIX and derivatives: ^D . In MS-DOS and derivatives: ^Z ). You may need to enter the EOF indicator twice.

If you are trying to read from a text file instead of the console, you'll want to either open the text file in your program, or use file redirection in your shell:

Option 1:

# If you always use the same input file:
with open("somefile.txt") as fp:
    for S in fp:
        ...

or

# If you always have exactly one command-line parameter:
with open(sys.argv[1]) as fp:
    for S in fp:

or, my favorite, because fileinput allows you to specify one, several, or no command-line parameters,

# If you want to specify file(s) on the command line
import fileinput
...
for S in fileinput.input():
    ...

Option 2:

$ python my_program.py < somefile.txt

or

C:\Users\me> python my_program.py < somefile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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