我试图从一个文本文件中读取行,但是我想,我被困在试图访问这些行的时候了。
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)在终点站,我被困在了
对于sys.stdin中的S:
如果您想知道,这段代码的目的是取行并将它们放入svg格式。所有的sys.stderr.write只是来自我的教授的规格。
我读的台词就像
“第0.0条1.0 2.0 3.0”
很多次了。
发布于 2016-03-30 21:43:42
在这一行:
for S in sys.stdin:你的程序没有卡住,它在等待输入。试着打字:
line 0.0 1.0 2.0 3.0接着是EOF指示器(在UNIX和派生语言中:^D )。在MS-DOS和衍生物:^Z中)。您可能需要输入两次EOF指示器。
如果您试图从文本文件中读取,而不是从控制台中读取,则需要在程序中打开文本文件,或者在shell中使用文件重定向:
备选案文1:
# If you always use the same input file:
with open("somefile.txt") as fp:
for S in fp:
...或
# If you always have exactly one command-line parameter:
with open(sys.argv[1]) as fp:
for S in fp:或者,我最喜欢的,因为fileinput允许您指定一个、几个或没有命令行参数,
# If you want to specify file(s) on the command line
import fileinput
...
for S in fileinput.input():
...备选案文2:
$ python my_program.py < somefile.txt或
C:\Users\me> python my_program.py < somefile.txthttps://stackoverflow.com/questions/36320112
复制相似问题