【问题标题】:Python stops reading .py scriptPython 停止读取 .py 脚本
【发布时间】:2013-11-26 11:49:08
【问题描述】:

我在“.py”文件中有一个 python 脚本,它基本上包含如下内容:

#import time and tcmodule.py module
import time
import tcmodule as tc

# Set Inputs (step 1):
tc.SetInput1(0)
tc.SetInput2(0)
tc.SetInput3(0)
time.sleep(0.250)
print(time.time())

# Set Inputs (step 2):
tc.SetInput1(3)
tc.SetInput2(6)
tc.SetInput3(12)
time.sleep(0.250)
print(time.time())

#the code continues the same way...

包含这 4 条指令的“设置输入”块重复了大约 900 次,因此文件很长但易于理解。它只是给一些变量一些值并等待 250 毫秒。

问题是,当我执行程序时,pythonwin 突然停止读取脚本(我知道是因为它突然停止打印时间),我不知道为什么会这样。最奇怪的是每次都停在不同的地方,所以我猜代码是可以的。有人知道代码有什么问题吗?

【问题讨论】:

  • 有什么原因不能用循环实现重复代码吗?
  • 我希望你循环重复 900 次而不是手动?你试过延长睡眠时间吗?
  • 5K 行并不多。您是否尝试过在没有pythonwin 的情况下使用普通的python 可执行文件来运行它?
  • 你打错了吗,而不是sleep(0.250)sleep(0250) 或类似的?
  • 我不能用循环来实现它,因为每个输入参数的值都来自另一个程序的跟踪,我只是解析跟踪来创建这个文件。我的意思是,这些值可能会以任何方式发生变化,而不仅仅是每 250 毫秒定期增加或减少值。

标签: python python-3.x


【解决方案1】:

我建议在此使用内存分析器。你可能内存不足。或者输入可能与 tc.SetInput 的预期不同。

#import time and tcmodule.py module
import time
import tcmodule as tc
from memory_profiler import profile

@profile
def my_func():
    tc.SetInput1(input1)
    tc.SetInput2(input2)
    tc.SetInput3(input3)
    time.sleep(0250)
    print(time.time())
def parseline():
   #take out the "pass" and return the 3 input values
   pass

with somefile.txt as txtfile:
   for line in file:
      try:
          input1,input2,input3=parseline(line)
          myfunc(input1,input2,input3)
      except Exception:
          #add error handling here and change the Exception.

【讨论】:

    【解决方案2】:

    您的 900 次迭代中的某个地方可能存在拼写错误。我建议你做这样的事情。这将使调试变得更加容易。

    # create a list of lists
    # each sublist will contain the three values that go with each SetInput function
    # add as many sublists as necessary 
    inputs = [[0, 0, 0], [3, 6, 12]]
    
    for inp in inputs:
        print "step", inp
        tc.SetInput1(inp[0])
        tc.SetInput2(inp[1])
        tc.SetInput3(inp[2])
        time.sleep(0.250)
        print(time.time())
    

    【讨论】:

      【解决方案3】:

      你真的应该重组你的程序,这样你就不需要经常重复自己。即使SetInput调用的参数每次都不一样,还是可以省不少的:

      import time
      import tcmodule as tc
      
      inputs = [
          (0, 0, 0),
          (3, 6, 12),
          # more values here
      ]
      
      for a, b, c in inputs:
          tc.SetInput1(a)
          tc.SetInput2(b)
          tc.SetInput3(c)
          time.sleep(0.250)
          print(time.time())
      

      您基本上需要将所有输入参数存储在一个大列表中并指定一次;然后你循环遍历这些值并编写你调用这些函数的块once。这也将防止您在文件深处的调用中出现任何键入错误。所以也许这已经解决了你的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 2015-11-27
        相关资源
        最近更新 更多