AttributeError when importing random - python

I'm having some issues importing random into my python program. I've read through other threads on this topic and for others, it seemed to stem from the file being named random.py.
My file is not named random.py. I have used print(random.file) to see where it is importing from, and it seems to be importing from C:\Python27\lib\random.pyc
I have tried moving that file out of the folder and it still does not work.
Here is the error:
Traceback (most recent call last):
File "C:/Python27/Projects/Test.py", line 4, in <module>
r1 = random.randomint(20,400)
AttributeError: 'module' object has no attribute 'randomint'
I have also tested in both powershell and the interpreter.
Here is the code snippet:
import random
import getpass
r1 = random.randomint(20,400)
r2 = random.randomint(20,400)
p = getpass.getpass(prompt='Please enter the correct value: %d * %d: ' %(r1,r2))
if p == (r1*r2):
print "Correct"
else:
print "Incorrect"
Can anyone help me out?
Edit: I'm an idiot. Thanks.

Correct name of the function is random.randint not random.randomint.

>> import random
>> random.randint(20,400)
76
AttributeError raise cause of error in function spelling. You should use randint instead of randomint.

Ha I had this too.. I wrote a python file to generate random numbers... but called it random.py so it did not work!... once I renamed it AND deleted random.pyc it worked fine

Related

ModuleNotFoundError: No module named '_beatbox'

I am trying to use python to connect with SF.
Saw some articles that show how to use it with beatbox library and I did install it.
However when trying to run simple code I'm getting error below.
Traceback (most recent call last):
File "c:/Users/user/hello/.vscode/hello.py", line 16, in <module>
import beatbox
File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\beatbox\__init__.py", line 1, in <module>
from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS, SoapFaultError, SessionTimeoutError
ModuleNotFoundError: No module named '_beatbox'
I navigate to the folder where the beatbox is installed and I see there the file _beatbox.py.
I think the file __init__.py try to import _beatbox but cannot find it for some reason.
Any idea how to solve it? What I'm missing?
Code:
import beatbox
sf_username = "xxxxxx"
sf_password = "xxxxxx"
sf_token = "xxxxxx"
def getAccount():
sf = beatbox._tPartnerNS
sf_client = beatbox.PythonClient()
password = str("%s%s" % (sf_password, sf_token))
sf_client.login(sf_username, sf_password)
accQuery = "Select Id,Name From Account limit 5"
queryResult = sf_client.query(accQuery)
print ("query result: " + str(queryResult[sf.size]))
for rec in queryResult[sf.records:]:
print str(rec[2]) + " : " + str(rec[3])
return
Can close the case. I first found that in python 3+ should use beatbox3. But then found additional errors (possible compatibility issues).
Since I notice it taking me too long, instead I tried using library simple-salesforce 0.74.2 to connect, and it worked perfect.
Probably, Python does not know where to search for the module. By default, only the sitepackages directory and your working directory is searched. You can resove this by placing a symbolic link to the beatbox package or moving it to the sitepackages directory
If you change the sitepackage folder name from "beatbox" to "_beatbox" this will solve your problem. You can then import it as: "import beatbox" and it will load in Python.

TypeError: 'module' object is not subscriptable

I'm using python version 3.6.
mystuff.py includes:
mystuff = {'donut': "SHE LOVES DONUTS!"}
mystuffTest.py includes this
import mystuff
print (mystuff['donut'])
The error that I receive when I run mystuffTest.py is as follows:
$ python3.6 mystuffTrythis.py
Traceback (most recent call last):
File "mystuffTrythis.py", line 3, in <module>
print (mystuff['donut'])
TypeError: 'module' object is not subscriptable
So far I haven't seen this exact error here on stackoverflow. Can anyone explain why I am getting this error?
import mystuff is importing the module mystuff, not the variable mystuff. To access the variable you'd need to use:
import mystuff
print(mystuff.mystuff['donut'])
EDIT: It's also possible to import the variable directly, using:
from mystuff import mystuff
print(mystuff['donut'])
I got this error because a later from __ import * statement imported a module which bound my variable to something else:
from stuff_a import d
from stuff_b import *
d['key']
In stuff_b.py, d was bound to a module, hence the error. Lesson learned: avoid importing * from modules.

Module has no attribute error in python3

contents of io.py
class IO:
def __init__(self):
self.ParsingFile = '../list'
def Parser(self):
f = open(ParsingFile, 'r')
print(f.read())
contents of main.py
import sys
sys.path.insert(0, "lib/")
try:
import io
except Exception:
print("Could not import one or more libraries.")
exit(1)
print("Libraries imported")
_io_ = io.IO()
When I run python3 main.py I get the following error:
Libraries imported
Traceback (most recent call last):
File "main.py", line 11, in <module>
_io_ = io.IO()
AttributeError: module 'io' has no attribute 'IO'
Any idea what's going wrong?
My file was called io. It seems that there already exists a package called io which caused the confusion.
Your package name (io) conflicts with the Python library's package with the same name, so you actually import a system package.
You can check this by printing io.__all__.
Changing io.py to something else is probably the best way to go to avoid similar problems. Otherwise, you can use an absolute path.
try
from io import IO
That worked for me when trying to import classes from another file
this has more information:
Python module import - why are components only available when explicitly imported?

Music21 Midi Error: type object '_io.StringIO' has no attribute 'StringIO'. How to fix it?

So, I've followed this question in order to get some sound playing with Music21, and here's the code:
from music21 import *
import random
def main():
# Set up a detuned piano
# (where each key has a random
# but consistent detuning from 30 cents flat to sharp)
# and play a Bach Chorale on it in real time.
keyDetune = []
for i in range(0, 127):
keyDetune.append(random.randint(-30, 30))
b = corpus.parse('bach/bwv66.6')
for n in b.flat.notes:
n.microtone = keyDetune[n.midi]
sp = midi.realtime.StreamPlayer(b)
sp.play()
return 0
if __name__ == '__main__':
main()
And here's the traceback:
Traceback (most recent call last):
File "main.py", line 49, in <module>
main()
File "main.py", line 44, in main
sp.play()
File "G:\Development\Python Development\Anaconda3\lib\site-packages\music21\mi
di\realtime.py", line 104, in play
streamStringIOFile = self.getStringIOFile()
File "G:\Development\Python Development\Anaconda3\lib\site-packages\music21\mi
di\realtime.py", line 110, in getStringIOFile
return stringIOModule.StringIO(streamMidiWritten)
AttributeError: type object '_io.StringIO' has no attribute 'StringIO'
Press any key to continue . . .
I'm running Python 3.4 x86 (Anaconda Distribution) on Windows 7 x64. I have no idea on how to fix this (But probably is some obscure Python 2.x to Python 3.x incompatibility issue, as always)
EDIT:
I've edited the import as suggested in the answer, and now I got a TypeError:
What would you recommend me to do as an alternative to "play some audio" with Music21? (Fluidsynth or whatever, anything).
You may be right... I think the error may actually be in Music21, with the way it handles importing StringIO
Python 2 has StringIO.StringIO, whereas
Python 3 has io.StringIO
..but if you look at the import statement in music21\midi\realtime.py
try:
import cStringIO as stringIOModule
except ImportError:
try:
import StringIO as stringIOModule
except ImportError:
from io import StringIO as stringIOModule
The last line is importing io.StringIO, and so later on the call to stringIOModule.StringIO() fails because it's actually calling io.StringIO.StringIO.
I would try to edit the import statement to:
except ImportError:
import io as stringIOModule
And see if that fixes it.
return stringIOModule.StringIO(streamMidiWritten)
AttributeError: type object '_io.StringIO' has no attribute 'StringIO'
Press any key to continue . . .
Please #Ericsson, just remove the StringIO from the return value and you are good to go.
It will now be:
return stringIOModule(streamMidiWritten)

Fixed: Python NameError, fixed AttributeError and got this?

FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.

Categories

Resources