Python cannot import from another file name not defined - python

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'

You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Related

ModuleNotFoundError: No module named 'SessionState

I am trying to make use of the streamlit SessionState, when I import SessionState. I get the following error: ModuleNotFoundError: No module named 'SessionState'
when using he SessionState
Here is a snipnet of my code:
from multiprocessing import Process
import streamlit as st
import SessionState
import time
import os
import signal
st.sidebar.title("Controls")
start = st.sidebar.button("Start")
stop = st.sidebar.button("Stop")
state = SessionState.get(pid=None)
Has anyone encountered this and how did you fix it? There are no resources online
https://docs.streamlit.io/en/stable/changelog.html?highlight=SessionState#version-0-54-0
Seems like you have to download this gist and put it into your project in order to use SessionState

Can't import modules in Python?

I'm following instructions and using files from: https://github.com/eBay/ebay-oauth-python-client
I'm getting error when I import: oauth2api, credentialutil, & model. This is step 3 in the above site.
import yaml, json
sys.path.insert(0, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient/model')
sys.path.insert(1, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/test')
sys.path.insert(2, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient')
import credentialutil
import model
import oauth2api
print(sys.path)
error message:
C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\python.exe C:/Users/kyle/PycharmProjects/app/app.py
Traceback (most recent call last):
File "C:/Users/kyle/PycharmProjects/app/app.py", line 10, in
import credentialutil
File "/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient\credentialutil.py", line 20, in
from model.model import environment, credentials
ModuleNotFoundError: No module named 'model.model'; 'model' is not a package
Process finished with exit code 1
The code runs if I only import model:
import yaml, json
sys.path.insert(0, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient/model')
sys.path.insert(1, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/test')
sys.path.insert(2, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient')
import model
print(sys.path)
no error message:
C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\python.exe C:/Users/kyle/PycharmProjects/app/app.py
['/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient/model', '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/test', '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient', 'C:\Users\kyle\PycharmProjects\app', 'C:\Users\kyle\PycharmProjects\app', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\lib\site-packages', 'C:\Users\kyle\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pymodel']
Process finished with exit code 0
I'm also getting a green line under oauthclient, and I don't know why. Everything is spelled correctly.
sys.path.insert(0, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient/model')
sys.path.insert(2, '/Users/kyle/PycharmProjects/app/ebay-oauth-python-client-master/oauthclient')
I can see two problems.
First, it seems that you are using Python under Windows, but you tried to insert a MacOS path to sys.path. Are you sure that paths like /Users/kyle/... really exist in your file system?
Second, you only need to insert the parent path, i.e. /path/to/ebay-oauth-python-client/oauthclient to your sys.path. In my local test, this works:
import yaml, json
import sys
sys.path.insert(0, r"C:\Users\guosh\Downloads\test\ebay-oauth-python-client\oauthclient")
import credentialutil
import model
import oauth2api
print(sys.path)
However, I would suggest you import the package as a whole, like below:
import yaml, json
import sys
sys.path.insert(0, r"C:\Users\guosh\Downloads\test\ebay-oauth-python-client")
import oauthclient
print(sys.path)

import ansible.module_utils in 2.2.1.0 as part of inventory module

Importing UTILS classes into Inventory - can it be done?
I have created a custom LDAP data importer as part of creating my inventory class. The LDAP schema we have wasn't similar enough to the LDAP plugin provided in samples.
My class is called ldapDataModule; the class is in:
/home/agt/ansible/agt_module_utils/ldapDataModule.py
My "$HOME/.ansible.cfg" file has the following:
module_utils = /home/agt/ansible/agt_module_utils
When running my Ansible inventory module, I get the following output:
ansible ecomtest37 -m ping
ERROR! Attempted to execute "/sites/utils/local/ansible/hosts" as
inventory script: Inventory script (/sites/utils/local/ansible/hosts) had
an execution error: Traceback (most recent call last):
File "/sites/utils/local/ansible/hosts", line 22, in
from ansible.module_utils import ldapDataModule
ImportError: No module named module.utils
The include statement inside hosts appears like this:
import copy
import ldap
import re
import sys
import operator
import os
import argparse
import datetime
import os.path
try:
import json
except:
import simplejson as json
from ansible.module_utils import ldapDataModule
class agtInventory(object):
RECOMENDATIONS?
I was able to do the following as a "work around". I'd still like to hear from Ansible guru's on proper use of "module_utils" variable from ansible.cfg
sys.path.insert(0, '/home/agt/ansible/agt_module_utils')
from ldapDataModule import ldapDataModule

importerror watson_developer_cloud Python

I have pip installed watson-developer-cloud, on python v3.5
I am simply trying to run one of the example codes: alchemy_data_news_v1.py
Link:https://github.com/watson-developer-cloud/python-sdk/tree/master/examples
import json
from watson_developer_cloud import AlchemyLanguageV1
alchemy_data_news = AlchemyDataNewsV1(api_key='api-key')
results = alchemy_data_news.get_news_documents(start='now-7d', end='now',
time_slice='12h')
print(json.dumps(results, indent=2))
results = alchemy_data_news.get_news_documents(
start='1453334400',
end='1454022000',
return_fields=['enriched.url.title',
'enriched.url.url',
'enriched.url.author',
'enriched.url.publicationDate'],
query_fields={
'q.enriched.url.enrichedTitle.entities.entity':
'|text=IBM,type=company|'})
print(json.dumps(results, indent=2))
I have also tried utilizing my own personal api-key and the result is the same:
File "c:\users\Joseph Sansevero\desktop\test.py", line 2, in
watson_developer_cloud import AlchemyLanguageV1 ImportError: No module
named watson_developer_cloud
Change your import statement to
from watson_developer_cloud import AlchemyLanguageV1
Alchemy language is a different api than AlchemyNews.
Head over to https://www.ibm.com/watson/developercloud/alchemydata-news/api/v1/?python#methods and you'll see the example has AlchemyNews imported.
Also make sure you install these packages using before running your code.

package import and NameError

I have some troubles with importation of self-made modules, I just can't see what I am doing wrong.
I have a package named basics, which has all my base classes
I have a second package named components, and every module in componentsuses the modules from basics.
I have a script file, located in another folder, which calls upon the basics and components modules.
I get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
execfile(filename, namespace)
File "H:/scripts/CIF_utilities/scripts/hello world.py", line 11, in <module>
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
File "H:\scripts\CIF_utilities\components\textwriter.py", line 23, in __init__
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
NameError: global name 'Layout' is not defined
There is my script: hello world.py
#hello world.py
import basics
from components.textwriter import *
TW=TextWriter(r'H:/scripts/CIF_utilities/components')
cell=TW.writeText('Hello World',30e3)
cell.draw()
layout=Layout()
layout.addCell(cell)
layout.workCell=cell
layout.exportCIF('hello world',os.getcwd())
textwriter.py is the one giving the error. In init, I load some data from a preformatted file using the Layout class (which will make the import)
in textwriter.py
#texwriter.py
import basics
import os, os.path, sys
import re
from numpy import *
from scipy import *
class TextWriter:
def __init__(self,pathToCIF=None):
if pathToCIF==None:
path=os.path.split(textwriter.__file__)[0]
else:
path=pathToCIF
###line that crashes is here
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
self.alphabet=layout.workCell
There is the layout.py class:
#layout.py
import basics
from numpy import *
from scipy import *
import Tkinter
import tkFileDialog
import os, os.path
import re
import datetime
class Layout:
countCell=0
#classmethod
def getNewNumber(self):
Layout.countCell+=1
return Layout.countCell
def __init__(self,File=None):
self.cellList=[]
self.layerList=[]
self.nameFile=""
self.comments=""
self.workCell=None
if File!=None:
self.importCIF(File)
the init.py of the basics package contains all the necessary importations:
#__init__.py in basics folder
from baseElt import *
from cell import *
from layout import *
from transformation import *
the init.py from components is empty
I am currently using the anaconda 64bits distribution (python 2.7 if I recall well)
Thanks for your much needed help!
Since Layout is imported in basics/__init__.py, it only exists in the basics namespace, not in helloworld.py. Either access it with
layout = basics.Layout()
or explicitly import Layout into helloworld.py with
from basics import Layout
In textwriter.py, you want to switch
layout=Layout(File=os.path.join(path,'alphabet.CIF'))
for
layout=basics.Layout(File=os.path.join(path,'alphabet.CIF'))
You may have similar problems along your code. it is good to note that it is not pythonic to use
from package import *
It is recommended to instead use
from package_or_module import specific_item
import package_or_module
Remember, if you import with regular import you have to use the module/package name to access the object you want (i.e. basics.Layout).

Categories