为什么此AssertionError异常不会继续

时间:2018-04-19 16:36:12

标签: python python-3.x

我有什么

我几天前发布了相关问题Is there a method to help make this Python logic run faster,并且在获得确认的解决方案之后,我已根据我的测试需求扩展了这个逻辑。

出于某种原因,我无法弄清楚如果这个Python正在运行,如果它得到一个AssertionError打印出Assertion Error然后continue再次返回逻辑,就无法告诉它。

from cpppo.server.enip.get_attribute import proxy_simple
from datetime import datetime
import time, csv, sys

host = "<PLC IP Address>"
TagName = "Tag Name"
RootCsvFile = "X:\\Some\\Folder\\Path\\"
source = proxy_simple(host)
prev = None

def csvwrite(v):
    with open(v[2],"a",newline='') as file:
        csv_file = csv.writer(file)
        csv_file.writerow([v[0],v[1]])

def ExecLoop(pr):
    prev = pr   
    while True:

        for message in source.read(TagName):

            try:
                val = message[0]
                timestr = str(datetime.now())
                if val != prev:
                    prev = val
                    YYYYMMDD = datetime.today().strftime('%Y%m%d')
                    CsvFile = RootCsvFile + TagName + "_" + YYYYMMDD + ".csv"
                    print(timestr, val, CsvFile)
                    csvwrite([timestr, val, CsvFile])

            except AssertionError:
                print("Assertion Error")
                continue           
ExecLoop(prev)

问题

由于这是通过VPN连接从PLC机器网络获取数据,因此每当VPN中断并且无法通过Python访问时,就会出现以下错误,似乎except AssertionError:是没有做我要求它做的事情,只是得到一个错误:

Traceback (most recent call last):   File
"~\GetTag-ToSQLDB&CSVEFile.py", line 63, in <module>
      ExecLoop(prev)   File "~\GetTag-ToSQLDB&CSVEFile.py", line 46, in ExecLoop
      for message in source.read(TagName):   File "~\Python\Python36-32\lib\site-packages\cpppo\server\enip\get_attribute.py",
line 431, in read
      for val,(sts,(att,typ,uni)) in reader:   File "~\Python\Python36-32\lib\site-packages\cpppo\server\enip\get_attribute.py",
line 606, in read_details
       depth=self.depth, multiple=self.multiple, timeout=self.timeout )): File
"~\Python\Python36-32\lib\site-packages\cpppo\server\enip\client.py",
line 1393, in operate

  for idx,dsc,req,rpy,sts,val in harvested:   File "~\Python\Python36-32\lib\site-packages\cpppo\server\enip\client.py",
line 1270, in pipeline 
complete, requests ) 

AssertionError: Communication ceased before harvesting all pipeline responses:   0/  1

我想要什么

我希望它能够在AssertionError时继续重试,因为通常在连接出现问题时,这只是短暂的几秒钟,或者是几分钟的自动每周电源周期运行Python的VPN客户端上的网络设备。

  • 我的问题:如何在此过程中获取except AssertionError:逻辑以打印内容,然后返回并尝试循环或其他任何内容?

    • 在出现错误时,流程停止并在屏幕上显示追溯详细信息,并在此问题的问题部分中发布。

我的假设

我假设问题与:

有关
  • 在{em> traceback 错误中指定的AssertionError文件中定义了client.py处理,并取代了脚本中脚本化的except AssertionError:逻辑

  • Try:Exception:逻辑位于while True循环内,然后位于for循环内的while True循环内。

其他细节(以防万一)

  • 此过程使用cpppo包。

  • 我正在使用Python版3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] Windows 10

  • 我正在测试IDLE正在运行此过程,而不是编译包或类似的东西。因此,我发布的逻辑保存为py文件,然后在IDLE中打开时按F5执行。

  • client.py相关的“假设”相关AssertionError逻辑(见第1269行):

    • 此处共享的逻辑clienty.py因为我的帖子太大了。

2 个答案:

答案 0 :(得分:1)

import pytest from model_mommy import mommy @pytest.fixture() def user(db): return mommy.make(User) class SiteAPIViewTestSuite: def test_create_view(self, client, user): assert Site.objects.count() == 0 post_data = { 'name': 'Stackoverflow' 'url': 'http://stackoverflow.com', 'user_id': user.id, } response = client.post( reverse('sites:create'), json.dumps(post_data), content_type='application/json', ) data = response.json() assert response.status_code == 201 assert Site.objects.count() == 1 assert data == { 'count': 1, 'next': None, 'previous': None 'results': [{ 'pk': 1, 'name': 'Stackoverflow', 'url': 'http://stackoverflow.com', 'user_id': user.id }] } 来电中发生了AssertionError。你需要用source.read(TagName) try块包装它:

except

答案 1 :(得分:1)

回溯说明了一切:您的except块不在可以看到异常的地方。具体来说,看一下

for message in source.read(TagName): File "~\Python\Python36-32\lib\site-packages\cpppo\server\enip\get_attribute.py", line 431, in read

错误发生在for循环中,但try位于循环内部。你有正确的想法将所有内容包装在while True中。解决方案是将for 移到 try内。

相关问题