Python中的for语句

1 投票
4 回答
573 浏览
提问于 2025-04-15 12:36

当一个exe文件运行时,它会输出一些内容。我想用下面的一些数字来运行这个程序,并打印出第54行(= blah)。但是它提示“process未定义”,我不太确定该怎么解决这个问题,想把我想要的内容打印到屏幕上。如果有人能提供一些代码或解决方法,我非常感谢!

for j in ('90','52.62263','26.5651','10.8123'):
    if j == '90':
        k = ('0',)
    elif j == '52.62263':
        k = ('0', '72', '144', '216', '288')
    elif j == '26.5651':
        k = (' 324', ' 36', ' 108', ' 180', ' 252')
    else:
        k = (' 288', ' 0', ' 72', ' 144', ' 216')

    for b in k:

        outputstring = process.communicate()[0]
        outputlist = outputstring.splitlines()
        blah = outputlist[53]

        cmd =  ' -j ' + str(j) + ' -b ' + str(b) + ' blah '

        process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)

        print cmd        

我想打印出例如:

-j 90 -az 0 (然后是blah包含的内容)blah就是第54行。第54行输出很多信息,主要是一些文字。我想在

-j 90 -az 0

之后,打印出第54行的内容。

@ Robbie: 第39行

blah = outputlist[53]

索引错误:列表索引超出范围

@ Robbie再次感谢你的帮助,抱歉给大家带来麻烦...

我甚至尝试了outputlist[2],但还是出现同样的错误 :/

4 个回答

2

你确定这样做是对的吗?

cmd =  ' -j ' + str(el) + ' -jk ' + str(az) + ' blah '

你的可执行文件在哪里?

2

下面这一行

outputstring = process.communicate()[0]

调用了process这个变量的communicate()方法,但process还没有被定义。你会在后面的代码中定义它。你需要把这个定义提前。

另外,你的变量名(jkjk)让人很困惑。

6

我忍不住想把这个整理一下。

# aesthetically (so YMMV), I think the code would be better if it were ...
# (and I've asked some questions throughout)

j_map = {
  90: [0], # prefer lists [] to tuples (), I say...
  52.62263: [0,  72, 144, 216, 288],
  26.5651: [324, 36, 108, 180, 252],
  10.8123: [288,  0, 72, 144, 216]
   }
# have a look at dict() in http://docs.python.org/tutorial/datastructures.html
# to know what's going on here -- e.g. j_map['90'] is ['0',]

# then the following is cleaner
for j, k in j_map.iteritems():
  # first iteration j = '90', k=[0]
  # second iteration j = '52.62263'', k= [0,...,288]
  for b in k:
    # fixed the ordering of these statements so this may actually work
    cmd = "program_name -j %f -b %d" % (j, b)
      # where program_name is the program you're calling
      # be wary of the printf-style %f formatting and
      #     how program_name takes its input
    print cmd
    process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
    outputstring = process.communicate()[0]
    outputlist = outputstring.splitlines()
    blah = outputlist[53]

你需要定义一下cmd这个东西——现在它试图执行类似“ -j 90 -b 288”的内容。我猜你想要的是cmd = "程序名称 -j 90 -b 288"

不知道这是否能解答你的问题,但希望能给你一些启发。

撰写回答