簡體   English   中英

Python3.6:_unify_values 中的文件“/usr/lib/python3.6/configparser.py”,第 1138 行

[英]Python3.6: File "/usr/lib/python3.6/configparser.py", line 1138, in _unify_values

我的腳本在使用 python 3.6 的 Pycharm 上運行良好,但是當我使用 Python3.6 從 ubuntu 16 運行時遇到了一些問題

錯誤:

python3.6 AttributeInsertion.py 正在加載庫模塊...回溯(最近一次調用):文件“/usr/lib/python3.6/configparser.py”,第 1138 行,在 _unify_values sectiondict = self._sections[section] KeyError :'測試配置'

 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "AttributeInsertion.py", line 49, in <module> jsonFeatureFile = readstringconfigfile('test_configurations', 'resourceName') File "AttributeInsertion.py", line 15, in readstringconfigfile fieldvalue = parser.get(section, field) File "/usr/lib/python3.6/configparser.py", line 781, in get d = self._unify_values(section, vars) File "/usr/lib/python3.6/configparser.py", line 1141, in _unify_values raise NoSectionError(section) configparser.NoSectionError: No section: 'test_configurations' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook from apport.fileutils import likely_packaged, get_recent_crashes File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module> from apport.report import Report File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module> import apport.fileutils File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module> from apport.packaging_impl import impl as packaging File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module> import apt File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module> import apt_pkg ModuleNotFoundError: No module named 'apt_pkg' Original exception was: Traceback (most recent call last): File "/usr/lib/python3.6/configparser.py", line 1138, in _unify_values sectiondict = self._sections[section] KeyError: 'test_configurations' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "AttributeInsertion.py", line 49, in <module> jsonFeatureFile = readstringconfigfile('test_configurations', 'resourceName') File "AttributeInsertion.py", line 15, in readstringconfigfile fieldvalue = parser.get(section, field) File "/usr/lib/python3.6/configparser.py", line 781, in get d = self._unify_values(section, vars) File "/usr/lib/python3.6/configparser.py", line 1141, in _unify_values raise NoSectionError(section) configparser.NoSectionError: No section: 'test_configurations'
from configparser import ConfigParser
from time import sleep
import json
import datetime
import requests

print('Loading library modules...')


def readstringconfigfile(section, field):
    try:
        parser = ConfigParser()
        configfilename = "..\\resources\\config.ini"
        parser.read(configfilename)
        fieldvalue = parser.get(section, field)
        print(f'Read string config file {fieldvalue}.')
        return fieldvalue[1:-1]
    except FileNotFoundError:
        print("Cannot find the config file.")


def replace_property_value(property, value):
    try:
        print('Old ' + property + ': ' + feature['properties'][property])  # print old value
        feature['properties'][property] = value  # override old value with new
        print('New ' + property + ': ' + feature['properties'][property])
    except Exception as e:
        print(repr(e))


def replace_payload_value(value):
    try:
        print('Old payload: ' + feature['properties']['payload'][0])
        feature['properties']['payload'][0] = value
        print('New payload: ' + feature['properties']['payload'][0])
    except Exception as e:
        print(repr(e))


def replace_user_name(value):
    try:
        print(feature['properties']['user']['name'])
        feature['properties']['user']['name'] = value
        print('New payload: ' + feature['properties']['user']['name'])
    except Exception as e:
        print(repr(e))


jsonFeatureFile = readstringconfigfile('test_configurations', 'resourceName')
jsonFeatureFile = "{0}{1}".format("..\\resources\\", jsonFeatureFile)
print(f'Resource file name is {jsonFeatureFile}.')

xyzSitBearerToken = readstringconfigfile('sit_configurations', 'xyzSitBearerToken')
xyzSitBearerToken = "\"" + xyzSitBearerToken + "\""
print(f'XYZ Bearer Token is {xyzSitBearerToken}.')

# Read FeatureCollection from JSON file:
print('Reading FeatureCollection from JSON file.')
with open(jsonFeatureFile, 'r', encoding='utf-8') as f:
    try:
        featureJson = json.load(f)
        print('Opening FeatureCollection.json', f)
        #print(f'Raw feature from resource file is {json.dumps(rawFeatureJson, indent=4)}.')
    except Exception as e:
        print(repr(e))

    try:
        headers = {'Content-Type': 'application/json',
                   'Authorization': 'Bearer {}'.format(xyzSitBearerToken)}
        e2eXyzSemiPerm = readstringconfigfile('sit_configurations', 'e2eXyzSemiPerm')
        e2eXyzBaseUrl = readstringconfigfile('sit_configurations', 'e2eXyzBaseUrl')
        xyzPutUrl = e2eXyzBaseUrl + e2eXyzSemiPerm + "/features"
        print(f'PUT request to XYZ url - {xyzPutUrl}.')

        for feature in featureJson['attributes']:

            currentTime = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%SZ')
            print(f'Current Time is {currentTime}.')
            replace_property_value("creationTime", currentTime)
            replace_property_value("startTime", currentTime)
            replace_property_value("informationType", "gottlieb-sit-semi-permanent")
            replace_payload_value("0xFF")
            replace_user_name("Pradeep Thomas Thundiyil")

            print(f'PUT Feature - {json.dumps(feature, indent=4)}.')
            response = requests.put(xyzPutUrl, json=feature, headers=headers)
            print(f'PUT feature to XYZ url - {response.url}.')
            print(f'PUT request response to XYZ {response.text}.')
            print(f'Response of PUT request to XYZ {response.status_code}.')
            print(response.json)
            print(f'Sleeping for 20 seconds.')
            sleep(20)
    except KeyError as e:
        print(repr(e))

這里變量“configfilename”中提供的路徑沒有指向 config.ini 文件的確切位置。 默認目錄可以根據環境/服務器/模塊/等而不同; 這不是您的程序所在的目錄。 因此,您可以使代碼指向文件所在的當前目錄。

您可以嘗試導入操作系統模塊(導入操作系統)並在您的變量“configfilename”中進行以下更改,該變量指向“resources”目錄下的“config.ini”文件。

configfilename = (os.path.join(os.path.dirname(__file__),'resources','config.ini'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM