Python Module attribute error - python-3.x

I know this topic has been came up many times, but I am totally stuck and need help. Please tell me what I have done wrong here and how to fix it. Thanks in advance.
# testcase1.py
import unittest
import sys
class Global:
b = 0
class Util_Case_ID(unittest.TestCase):
def setUp(self):
sys.path.insert(0, 'C:/**/views')
sys.path.insert(0, 'C:/**/app')
sys.path.insert(0, 'C:/**/tests')
from app.views.utility import method_a
Global.b = len(method_a())
def test1(self):
self.assertEqual(Global.b, 11)
def tearDown(self):
sys.path.remove('C:/***/app/views')
sys.path.remove('C:/***/app')
sys.path.remove('C:/*/tests')
if __name__ == "__main__":
unittest.main()
AttributeError: module 'UnitTests' has no attribute 'testcase1'
The Traceback is as follows:
Traceback (most recent call last):
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\utrunner.py", line 167, in <module>
all.addTests(testLoader.loadTestsFromTestClass(getattr(module, a[1])),
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\loader.py", line 108, in loadTestsFromTestClass
return self.suiteClass(ContextList(cases, context=cls))
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 253, in __call__
return self.makeSuite(tests, context, **kw)
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 291, in makeSuite
for ancestor in self.ancestry(context):
File "C:\Users\******\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 269, in ancestry
yield resolve_name('.'.join(ancestors))
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\util.py", line 70, in resolve_name
obj = getattr(obj, part)
AttributeError: module 'UnitTests' has no attribute 'testcase1'
Process finished with exit code 1

Related

Executing SPARQL queries with the wikibaseintegrator package on a local Wikibase instance

I'm attempting to run a SPARQL query using the Python package wikibaseintegrator (version 0.10.0).
The program is written as follows:
from wikibaseintegrator.wbi_config import config as wbi_config
from wikibaseintegrator import wbi_login, wbi_core
wbi_config['MEDIAWIKI_API_URL'] = 'http://localhost/database_name/api.php'
wbi_config['SPARQL_ENDPOINT_URL'] = 'http://localhost:8989/database_name/sparql'
wbi_config['WIKIBASE_URL'] = 'http://wikibase.svc'
temp_username = "placeholder_username"
temp_password = "placeholder_password"
def main():
login_instance = login()
sparql_str = """
SELECT ?item ?itemLabel
WHERE
{
?item wdt:P98 wd:Q45.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
"""
sparql_results = run_sparql_query(sparql_str)
print(sparql_results)
def login(username=temp_username, password=temp_password):
login_instance = wbi_login.Login(user=username, pwd=password)
return login_instance
def run_sparql_query(sparql_str):
sparql_results = wbi_core.ItemsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
return sparql_results
# MAIN
if __name__ == "__main__": main()
When I run this though, the error I get is:
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.ItemsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'ItemsEngine'
However, the documentation (https://github.com/LeMyst/WikibaseIntegrator) seems to imply that this is the correct way to format the query. Any help in diagnosing would be much appreciated!
EDIT 1: The documentation says it's in the ItemEngine (The method wbi_core.ItemEngine.execute_sparql_query()), but the program itself seems to show it being in the FuctionsEngine
I have tried all of these variations, with the error being the same:
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.FuctionsEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'FuctionsEngine'
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.ItemEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: type object 'ItemEngine' has no attribute 'execute_sparql_query'
$ python database_script.py
Traceback (most recent call last):
File "database_script.py", line 52, in <module>
if __name__ == "__main__": main()
File "database_script.py", line 40, in main
sparql_results = run_sparql_query(sparql_str)
File "database_script.py", line 48, in run_sparql_query
sparql_results = wbi_core.FunctionEngine.execute_sparql_query(sparql_str, endpoint=wbi_config['SPARQL_ENDPOINT_URL'])
AttributeError: module 'wikibaseintegrator.wbi_core' has no attribute 'FunctionEngine'
EDIT 2: The larger issue seemed to be the lack of an install for the SPARQL service since I had gotten it running with WAMP64. I installed a Docker instance and it's been a decent amount easier out of the box (except the export of the WAMP64 version and import into the Docker instance).

Unable to run python file

I have been trying to run a python script, but I keep on getting the following error.
Error:
Traceback (most recent call last):
File "cloud_copasi/background_daemon/cloud_copasi_daemon.py", line 18, in <module>
django.setup()
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "/Users/cloudcopasi/cloud-copasi/venv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'web_interface'
The script file which I am trying to run (cloud_copasi_daemon) is:
import sys, time
import django
django.setup()
from tools.daemon import Daemon
import tools.background_script
from tools.response import RemoteLoggingResponse
from cloud_copasi import settings
import logging
log=logging.getLogger(__name__)
class MyDaemon(Daemon):
#Set the level we wish to log at. Logs are sent back to the central server
#Choices are all, debug, info, error, none
def __init__(self, *args, **kwargs):
return super(MyDaemon, self).__init__(*args, **kwargs)
def stop(self, *args, **kwargs):
return super(MyDaemon, self).stop(*args, **kwargs)
def run(self):
log.debug('Daemon running')
while True:
min_repeat_time = settings.DAEMON_POLL_TYME #Seconds
start_time = time.time()
try:
tools.background_script.run()
log.debug('Background script finished')
except Exception as e:
log.exception(e)
finish_time = time.time()
difference = finish_time - start_time
if difference < min_repeat_time:
time.sleep(min_repeat_time - difference)
if __name__ == "__main__":
daemon = MyDaemon('/tmp/Cloud-COPASI.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print ("Unknown command")
sys.exit(2)
sys.exit(0)
else:
print("usage: %s start|stop|restart" % sys.argv[0])
sys.exit(2)
"web_interface" is the Django App and I have verified that the path referring to it is correct. I don't know where else do I need to fix the file path to get this python script to work.
I am having the same problem on Mac OS Big Sur (running Python 3.8) as well as on Linux CentOS (running Python 3.6).
Any help is much appreciated.
When you are trying to bootstrap django like this you need to make sure to set the environment variable PYTHONPATH to include the folder where web_interface lives. I'm guessing that your cloud_copasi_daemon.py is in a different folder than web_interface so when you run python cloud_copasi_daemon.py it looks in the immediate folder in which you invoked the script and can't find it.

Error while creating a service using nameko for Pysnmp get_request--Attempted "nameko_entrypoints" operation on ASN.1 schema object

I am new to pysnmp and nameko. I have been assignment a work to create a service in nameko framework to perform snmp get_request using pysnmp library.
Below is the code i have tried
from pysnmp.hlapi import *
from nameko.rpc import rpc
class GreetingService(object):
name = "greeting_service"
#rpc
def getFunc(oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(SnmpEngine(),
CommunityData('public', mpModel=0),
UdpTransportTarget(('snmp.live.gambitcommunications.com', 161)),
ContextData(),
ObjectType(ObjectIdentity('SNMPv2-MIB', oid, 0)))
)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(),
errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
else:
for varBind in varBinds:
print(' = '.join([x.prettyPrint() for x in varBind]))
if __name__ == "__main__":
getFunc('sysName')
when i try to start the service using terminal with the following command
$ nameko run helloworld
I get the following error message.
syed#syed-ThinkPad-E480:~/Pysnmp$ nameko run helloworld
Traceback (most recent call last):
File "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
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 24, 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 "/home/syed/.local/bin/nameko", line 11, in <module>
sys.exit(main())
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/main.py", line 112, in main
args.main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/commands.py", line 110, in main
main(args)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 181, in main
import_service(path)
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 71, in import_service
if inspect.getmembers(potential_service, is_entrypoint):
File "/usr/lib/python3.7/inspect.py", line 354, in getmembers
if not predicate or predicate(value):
File "/home/syed/.local/lib/python3.7/site-packages/nameko/cli/run.py", line 35, in is_entrypoint
return hasattr(method, ENTRYPOINT_EXTENSIONS_ATTR)
File "/home/syed/.local/lib/python3.7/site-packages/pyasn1/type/base.py", line 221, in __getattr__
raise error.PyAsn1Error('Attempted "%s" operation on ASN.1 schema object' % attr)
pyasn1.error.PyAsn1Error: Attempted "nameko_entrypoints" operation on ASN.1 schema object
Please help me out to understand weather what i have tried is correct way or else it is wrong.. If so how to rectify the mistake.
Any help will be appreciable.
Thanks in advance
It has something to do with the way how nameko hooks up your code...
It seems to try looking up nameko_entrypoints attribute at all objects it can find in your module eventually running into ASN.1 schema objects (which are sacred and should not be used for anything other than blueprinting purposes).
My suggestion would be to replace from pysnmp.hlapi import * with specific imports of pysnmp classes/functions you are using in your code. That should hopefully hide fragile pieces out of nameko's sight.

Selenium Testing in Firefox under session id

E
======================================================================
ERROR: test_LoginCorrect (__main__.LoginCorrect)
----------------------------------------------------------------------
Traceback (most recent call last):
File "demo.py", line 12, in test_LoginCorrect
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 248, in
start_session
self.session_id = response['sessionId']
TypeError: string indices must be integers
----------------------------------------------------------------------
Ran 1 test in 20.878s
//Formatting is not properly done
FAILED (errors=1)
My test case file :
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class LoginCorrect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Remote(command_executor='http://0.0.0.0:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX)
def test_LoginCorrect(self):
user ="shubh"
pwd= "sha123#56su"
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
driver.get("http://0.0.0.0:8000/login")
elem = driver.find_element_by_id("id_username")
elem.send_keys(user)
elem = driver.find_element_by_id("id_password")
elem.send_keys(pwd)
driver.find_element_by_class_name('btn-block').click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
My machine has Linux 16.04LTS and selenium 3.3.0
Can somebody figure out this problem.

Python 3 multiprocessing error

I'm trying to run this code taken form python doc
https://docs.python.org/3.6/library/multiprocessing.html
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
but here what I get:
main line
module name: __main__
parent process: 15744
process id: 7344
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="__mp_main__")
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 261, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "C:\Users\SomeUser\AppData\Local\Programs\Python\Python36-32\lib\runpy.py", line 231, in _get_code_from_file
with open(fname, "rb") as f:
OSError: [Errno 22] Invalid argument: 'C:\\Users\\SomeUser\\<stdin>'
what am I doing wrong? I use python 3.6.1.

Resources