I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!
Related
I am trying to make the call
from azure.storage.fileshare import ShareDirectoryClient
shrdDirClient = ShareDirectoryClient.from_directory_url
(detailedFileURI,snapshot=None, credential=None)
but resulted in the error above.
I tried
if hasattr(ShareDirectoryClient, 'from_directory_url'):
print("Present")
But it did not go into the loop.
My full code is too long. This is another approach I tried resulting in 'str' object is not callable error
from azure.storage.fileshare import ShareDirectoryClient
from datetime import timedelta,datetime
now = datetime.now(timezone('UTC'))
sasToken = generate_share_sas(accountName, shareName, accountKey,\
permission=AccountSasPermissions(read=True, \
write=False, \
delete=False, \
list=True, create=True), expiry=now + timedelta(days=3650)\
)
accountURL = "https://nsclusterhdistorage.file.core.windows.net"
shareName = "dev-archived-data"
detailedFileURI = accountURL+'/'+shareName
sh = ShareDirectoryClient()
sh.from_directory_url(detailedFileURI,snapshot=None, credential=sasToken)
I am relatively new to python azure storage file share.
can someone help
Sorry, I can't reproduce this.
I ran the following code:
from azure.storage.fileshare import ShareDirectoryClient
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
and it generated the following error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 4, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 164, in from_directory_url
credential=credential, **kwargs)
File "C:\Python37\lib\site-packages\azure\storage\fileshare\_directory_client.py", line 96, in __init__
raise ValueError("Please specify a share name.")
ValueError: Please specify a share name.
Now clearly this isn't successful execution. If I'm honest, I don't know what to set detailedFileURI to. But that's not the point. The point is that the code sample above is enough to prove that I can get in to the from_directory_url method, and this is clear from the traceback.
However, if I run the following code:
from azure.storage.fileshare import ShareDirectoryClient
ShareDirectoryClient = "some string"
detailedFileURI = "Something"
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
then I do encounter the same error:
Traceback (most recent call last):
File "D:\StackOverflow\azure_storage_test.py", line 5, in <module>
shrdDirClient = ShareDirectoryClient.from_directory_url(detailedFileURI,snapshot=None, credential=None)
AttributeError: 'str' object has no attribute 'from_directory_url'
Of course, there's not a lot of point in importing ShareDirectoryClient if you're then going to assign a string to it. You may as well remove the import statement. However, doing this reproduces your error message. In the absence of any further code in your question I can only conclude that your code does the same as this, although perhaps more subtly.
The only other suggestion I have is that your installation of the azure-storage-file-share package has somehow got broken. If you run a Python script containing the following two lines only, you should get either <class 'type'> or <class 'str'> as output. I get <class 'type'>, and I would expect that anyone else using this package would get the same. However, if you get <class 'str'>, then it is likely that the package has got corrupted and you may want to try reinstalling it.
from azure.storage.fileshare import ShareDirectoryClient
print(type(ShareDirectoryClient))
For some reason ‘ ShareDirectoryClient’ is of type {string}. You either import it as a string, i.e. ‘ azure.storage.fileshare’ simply has this defined as a string, or, you assign it to a string later in your code (not visible in the part that has been shared). Please try this:
X = ‘some_string’
X()
… and you will get the string-is-not-callable error which means a string cannot be invoked (i.e. it is not a function one can call)
Then another experiment:
Y = ‘another_string’
Y.bla()
… and you get the other error that a string object has no attribute named ‘bla’.
In Python everything is an object. If you define
class MyClass()
pass
And then try ‘MyClass.bla()’ you will get MyClass does does not have attribute ‘bla’.
Can you try to import ShareDirectoryClient and then type(ShareDirectoryClient) and we’ll see what type of object gets imported.
I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC
I recently made a program using an external document with pickle. But when it tries to load the file with pickle, I got this error (the file is already existing but it also fails when the file in't existing):
python3.6 check-graph_amazon.py
a
b
g
URL to follow www.amazon.com
Product to follow Pool_table
h
i
[' www.amazon.com', ' Pool_table', []]
p
Traceback (most recent call last):
File "check-graph_amazon.py", line 17, in <module>
tab_simple = pickle.load(doc_simple)
io.UnsupportedOperation: read
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "check-graph_amazon.py", line 42, in <module>
pickle.dump(tab_simple, 'simple_data.dat')
TypeError: file must have a 'write' attribute
Here is the code :
import pickle5 as pickle
#import os
try:
print("a")
with open('simple_data.dat', 'rb') as doc_simple:
print("b")
tab_simple = pickle.load(doc_simple)
print("c")
print(tab_simple)
print("d")
URL = tab_simple[0]
produit_nom = tab_simple[1]
tous_jours = tab_simple[2]
print("f")
except :
print("g")
URL = str(input("URL to follow"))
produit_nom = str(input("Product to follow"))
with open('simple_data.dat', 'wb+') as doc_simple:
print("h")
#os.system('chmod +x simple_data.dat')
tab_simple = []
tab_simple.append(URL)
tab_simple.append(produit_nom)
tab_simple.append([])
print(tab_simple)
print("c'est le 2")
print("p")
pickle.dump(tab_simple, 'simple_data.dat')
print("q")
The prints are here to show which lines are executed. The os.system is here to allow writing on the file but the error is persisting.
I don't understand why it's said that the document doesn't have a write attribute because I opened it in writing mode. And I neither understand the first error where it can't load the file.
If it can help you the goal of this script is to initialise the program, with a try. It tries to open the document in reading mode in the try part and then set variables. If the document doesn't exist (because the program is lauched for the first time) it goes in the except part and create the document, before writing informations on it.
I hope you will have any clue, including changing the architecture of the code if you have a better way to make an initialisation for the 1st time the program is launched.
Thanks you in advance and sorry if the code isn't well formated, I'm a beginner with this website.
Quote from the docs for pickle.dump:
pickle.dumps(obj, protocol=None, *, fix_imports=True)
Write a pickled representation of obj to the open file object file. ...
...
The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.
So, you should pass to this function a file object, not a file name, like this:
with open("simple_data.dat", "wb"): as File:
pickle.dump(tab_simple, File)
Yeah, in your case the file has already been opened, so you should write to doc_simple.
I'm trying to make a mixWord function and I'm getting an error saying
NameError: name 'word' is not defined
What am I missing from here?
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
Traceback (most recent call last):
File "", line 1, in
mixWord (word)
NameError: name 'word' is not defined
The problem is PEBKAC - exactly what form, is for you to find out.
That is, the code executed is not the same as the code posted; the posted code works as expected:
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
mixWord("PEBKAC")
So, find out why:
Has the file been saved?
Has the file been saved to the correct location?
Is the file from the correct location being run?
Is the error from different code entirely?
Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).
After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.
I think the problem is that you are calling mixWord(word) without defining any word variable.
Edit
So I did try again, with a new file called test2.py and it works. I packaged repoman , and test.py is in the src folder. I modified test.py after I created and installed my repoman egg. I think that's the problem. But thanks for the help. Do you guys think that's the exact reason?
import unittest
import requests
from repoman.core import ultraman, supported
from repoman.ext import writefile,locate_repo
class TestWriteFile(unittest.TestCase):
def setUp(self):
self.username = 'dummy'
self.password = 'dummy'
self.remote = 'http://192.168.1.138:6666/scm/hg/NCL'
def test_scm_permission(self):
"""
Test SCM login.
"""
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
if __name__ == '__main__':
unittest.main()
Running python test.py I get this error:
Traceback (most recent call last):
File "test.py", line 7, in <module>
class TestWriteFile(unittest.TestCase):
File "test.py", line 19, in TestWriteFile
self.assertTrue(r.ok)
NameError: name 'self' is not defined
I don't think I need to overwrite __init__ function, do I? What's causing this? Why is self not defined? I already declared my superclass unittest.TestCase
Thanks.
I basically learned it from the official sample: Unittest - Basic Example
I'm not sure where the problem is coming from -- whether it's a copying error or the wrong test.py is being executed [update: or some mixed tabs-and-spaces issue, I can never figure out when those get flagged and when they don't] -- but the root cause is almost certainly an indentation error.
Note that the error message is
NameError: name 'self' is not defined
and not
NameError: global name 'self' is not defined
which #Rik Poggi got. This is exactly what happens if you move the self.assertTrue one level in/up:
~/coding$ cat test_good_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_good_indentation.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
versus
~/coding$ cat test_bad_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_bad_indentation.py
Traceback (most recent call last):
File "test_bad_indentation.py", line 3, in <module>
class TestWriteFile(unittest.TestCase):
File "test_bad_indentation.py", line 8, in TestWriteFile
self.assertTrue(1)
NameError: name 'self' is not defined
I don't think that what you showed is the actual code that get executed.
I and others belive that, for a couple of reasons:
If self.assertTrue(r.ok) fails then the line before will too. Therefore self.assertTrue(r.ok) won't execute. (as David Heffernan said)
And because your code looks fine.
I'd say that you probably made a typo of this kind:
def test_scm_permission(self):
^
|
and wrote something here that's not self
In some file that get executed instead of the one you're showing.
Take a look at this example:
# test.py
class MyClass:
def func(sel): # typo error here
self.name = 10
obj = MyClass()
obj.func()
And when I tried to run:
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
obj.func()
File "test.py", line 4, in func
self.name = 10
NameError: global name 'self' is not defined
Having a traceback similar to yours.
Note: Also if I'm not counting wrong self.assertTrue(r.ok) is on line 18, instead of line 19 (which is the number showed in your traceback).
This is a rewording of David Heffernan's comment.
The code you posted cannot be the cause of that traceback.
Consider these two lines from your code:
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The traceback says the error (NameError: name 'self' is not defined)
occurs on the second line (self.assertTrue(r.ok)). However, this cannot have been the case because the first line refers to self. If self were not defined, we would not get past the first line.
Therefore, the code you posted is not the code you ran.
This is an old question, but thought I'd add my two cents as it was not mentioned here. I agree with others that there is some type of spelling error in the original code. Look at this code carefully:
import unittest
import requests
class TestWriteFile(unittest.TestCase):
def setup(self):
self.username = 'dummy'
def test_scm_permission(self):
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The code appears okay at first glance (and lint tools will not complain); however, I wrote setup, instead of setUp (note the capital U). This causes self.username not to be defined in the test_scm_permission context, because python did not automatically call my mispelled function name. This is something else to check if you're running into this type of error, but are certain you've defined the class members correctly.
I had the same problem, but not with self. It was a regular variable, defined the line before the error occured.
It was apparently due to ... mixin tabs and spaces.
I replaced all tabs by 4 spaces, and the problem disappeared.
For some unspecified reason, instead of the traditional indentation error, I had this one.