简体   繁体   中英

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

My script is working fine on Pycharm with python 3.6, but has some issues when i run from ubuntu 16 using Python3.6

Error:

python3.6 AttributeInsertion.py Loading library modules... 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' 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))

Here the path provided in the variable 'configfilename' is not pointing towards the exact location of config.ini file. Default directories can be different according to the environments/servers/modules/etc; which is not the directory in which your program exists. So, you can make the code point towards the current directory where the file exists.

You can try by importing OS module(import os) and following changes in your variable 'configfilename' which directs to 'config.ini' file under the directory 'resources'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM