I'm trying to use a global variable. I've declared it as global to begin with and the declare it at such at each mention, but I get a NameError after the first function completes. Here's the code, and I think I've gone stare crazy but I can't seem to find the problem.
def on_servername_insertatcursor(self, widget):
global output
output = StringIO.StringIO()
servername = widget.get_text()
output.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
global output
output.write("USHARE_IFACE="+netif+'\n')
def on_port_insertatcursor(self, widget):
global output
port = widget.get_text()
output.write("USHARE_PORT="+port+'\n')
def on_telprt_insertatcursor(self, widget):
global output
telprt = widget.get_text()
output.write("USHARE_TELNET_PORT="+telprt+'\n')
def on_dirs_insertatcursor(self, widget):
global output
dirs = widget.get_text()
output.write("USHARE_DIR="+dirs+'\n')
def on_iconv_toggled(self, widget):
global output
iconv = widget.get_active()
if iconv == True:
output.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
else:
output.write("USHARE_OVERRIDE_ICONV_ERR="+"False"+'\n')
def on_webif_toggled(self, widget):
global output
webif = widget.get_active()
if webif == True:
output.write("USHARE_ENABLE_WEB="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_WEB="+"no"+'\n')
def on_telif_toggled(self, widget):
global output
telif = widget.get_active()
if telif == True:
output.write("USHARE_ENABLE_TELNET="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_TELNET="+"no"+'\n')
def on_xbox_toggled(self, widget):
global output
xbox = widget.get_active()
if xbox == True:
output.write("USHARE_ENABLE_XBOX="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_XBOX="+"no"+'\n')
def on_dlna_toggled(self, widget):
global output
dlna = widget.get_active()
if dlna == True:
output.write("USHARE_ENABLE_DLNA="+"yes"+'\n')
else:
output.write("USHARE_ENABLE_DLNA="+"no"+'\n')
def on_commit_clicked(self, widget):
commit = output.getvalue()
logfile = open('/home/boywithaxe/Desktop/ushare.conf','w')
logfile.write(commit)
def on_endprogram_clicked(self, widget):
sys.exit(0)
What's amazing is that when insertatcursor (coming from Gtk.TextBuffer.insert_at_cursor() ) is replace with activate, the code works perfectly, except I don't want to have the user have to press enter after every data input.
EDIT. The Traceback is as follows
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 58, in on_netif_changed
output.write("USHARE_IFACE="+netif+'\n')
NameError: global name 'output' is not defined
Having made the changes suggested by #jdi (Thank you btw, I see the logic behind that), the Traceback I get is as follows:
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 55, in on_netif_changed
OUTPUT.write("USHARE_IFACE="+netif+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 72, in on_iconv_toggled
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 79, in on_webif_toggled
OUTPUT.write("USHARE_ENABLE_WEB="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 86, in on_telif_toggled
OUTPUT.write("USHARE_ENABLE_TELNET="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 93, in on_xbox_toggled
OUTPUT.write("USHARE_ENABLE_XBOX="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 100, in on_dlna_toggled
OUTPUT.write("USHARE_ENABLE_DLNA="+"yes"+'\n')
NameError: global name 'OUTPUT' is not defined
Traceback (most recent call last):
File "/home/boywithaxe/Developer/Quickly/broadcast/broadcast/BroadcastWindow.py", line 105, in on_commit_clicked
commit = OUTPUT.getvalue()
NameError: global name 'OUTPUT' is not defined
Your code example doesn't require a global. Just remove it. The only time you need to use the global keyword in a function is if you are going to assign to it.
OUTPUT = StringIO.StringIO()
def on_servername_insertatcursor(self, widget):
servername = widget.get_text()
OUTPUT.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
OUTPUT.write("USHARE_IFACE="+netif+'\n')
def on_port_insertatcursor(self, widget):
port = widget.get_text()
OUTPUT.write("USHARE_PORT="+port+'\n')
def on_telprt_insertatcursor(self, widget):
telprt = widget.get_text()
OUTPUT.write("USHARE_TELNET_PORT="+telprt+'\n')
def on_dirs_insertatcursor(self, widget):
dirs = widget.get_text()
OUTPUT.write("USHARE_DIR="+dirs+'\n')
def on_iconv_toggled(self, widget):
iconv = widget.get_active()
if iconv == True:
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"True"+'\n')
else:
OUTPUT.write("USHARE_OVERRIDE_ICONV_ERR="+"False"+'\n')
Even if you wanted to be able to reset your StringIO object in a function, it still wouldn't require an assignment or global keyword:
def reset_output(self):
OUTPUT.seek(0)
OUTPUT.truncate()
Proof that it works
import StringIO
OUTPUT = StringIO.StringIO()
def foo():
OUTPUT.write('foo')
def bar():
OUTPUT.write('bar')
def print_output():
print OUTPUT.getvalue()
def reset_output():
OUTPUT.seek(0)
OUTPUT.truncate()
if __name__ == "__main__":
foo()
bar()
print_output()
reset_output()
print_output()
Output
$ python test.py
foobar
$
Try moving output = StringIO.StringIO() outside and above all the functions in the file.
Well, the problem with the question is unfortunate indenting :) Looking at PyGTK docs shows that the on_... functions shown are indeed methods of a class, not global functions, so the "global" variable is probably not really global but also a member of the class (just look at the self parameter in method definitions).
I gave a more detailed answer on askubuntu, here's a code snippet which shows what needs to be done:
class MyApp(gtk.Window):
output = None
def __init__(...):
...
self.output = StringIO.StringIO()
def on_servername_insertatcursor(self, widget):
servername = widget.get_text()
self.output.write("USHARE_NAME="+servername+'\n')
def on_netif_changed(self, widget):
netif = widget.get_active_text()
self.output.write("USHARE_IFACE="+netif+'\n')
There's absolutely no PyGTK-specific or signals-specific magic involved :)
Related
I want to jump from def number1 to def number2.
I tried this:
def number1():
print("from here to ")
number2()
number1()
def blablabla():
print("blablabla")
blablabla()
def number2():
print("here")
number2()
but I received this error:
Traceback (most recent call last):
File "C:\Users\i5 9400f\Documents\projetos python\test.py", line 4, in <module>
number1()
File "C:\Users\i5 9400f\Documents\projetos python\test.py", line 3, in number1
number2()
^^^^^^^
NameError: name 'number2' is not defined. Did you mean: 'number1'?
from here to
Process finished with exit code 1
I tried using the number2()
it did not work
Python just run your code from top to bottom sequentially so if you try to access to something that is only defined later you won't succeed. What you need to do is to define all the functions first then call them later :
def number1():
print("from here to ")
number2()
def blablabla():
print("blablabla")
def number2():
print("here")
number1()
blablabla()
number2()
def number1():
print("from here to ")
number2()
def number2():
print("here")
def blablabla():
print("blablabla")
number1()
blablabla()
number2()
###Before runnıng def functıons, you should put them at the top of your processes
I'm trying but it's not working. I have the following code line:
class Run:
def Method(self, choice):
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.start().LoadJson['zip'])
And this is variable, and is within another class, and another function:
class Host_Method:
def start(self):
My_API = requests.get("http://ip-api.com/json/%s" % socket.gethostbyname(sys.argv[2]))
LoadJson = json.loads(My_API.content)
The error:
Traceback (most recent call last):
File "InfoIP.py", line 78, in <module>
elif sys.argv[1] == "-h": Run().Method(Host_Method())
File "/Pentest/InfoIP2/Libraries/InfoIP_Functions.py", line 159, in Method
print "%sZip :\t%s%s\n".decode('utf-8') % (Basic_Green, White, choice.LoadJson['zip'])
AttributeError: Host_Method instance has no attribute 'LoadJson'
You probably want them to be stored in an instance variable (self....). And you probably want your start to be an __init__ method. Your corrected class could look like:
class HostMethod:
def start(self):
self.my_API = requests.get("http://ip-api.com/json/{0}".format(socket.gethostbyname(sys.argv[2])))
self.load_json = json.loads(self.my_API.content)
Then, you could do:
class Run:
def Method(self, choice):
print "{0}Zip :\t{1}{2}\n".decode('utf-8').format(Basic_Green, White, choice.load_json['zip'])
a = Run()
a.method(HostMethod())
See also:
https://docs.python.org/3.4/tutorial/classes.html
I'm trying to read a file with python, by posting the address in input line. In my plan, when I press the button, program will read the file, make all needed work with the text inside the first file, and write the result into a second one:
import Tkinter
class Generator(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent=parent
self.initialize()
def initialize(self):
self.grid()
self.addressLink = Tkinter.StringVar()
self.entry=Tkinter.Entry(self,textvariable=self.addressLink)
self.entry.grid(column=0,row=0,sticky='EW')
self.entry.bind("<Return>", self.OnPressEnter)
self.entry.bind(".", self.OnPressDot) # verify that address was accepted
self.addressLink.set(u"Enter your input file's address here!")
button=Tkinter.Button(self,text=u'Generate the list!',command=self.OnButtonClick)
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self, textvariable=self.labelVariable,
anchor="w",fg="white",bg="blue")
label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Enter Address !")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
def ProgramBody(readlink):
excelWrite=open('/Users/BUR/Desktop/final_TK.txt','w')
z=0
for index, line in enumerate(readlink, start=0):
keywrds=[]
title=line.split("+")
title=[lines.strip()for lines in title]
print title[0]
print index
header="Title"+"\t"+"Price equal to title:"+"\t"+"keyword1"+"\t"+"keyword2"+" \t"+"keyword3"+"\t"+"keyword4"+"\t"+"keyword5\t"+"Manufacturer Part Number\n"
exclWrt(header)
excelWrite.close()
def FileRead(tsink):
excelRead=open(tsink,'r')
print tsink
ProgramBody(tsink)
def OnButtonClick(self):
link=(self.addressLink.get())
# print link
self.labelVariable.set(link+" (Here is your button press!) ")
FileRead(link)
def OnPressEnter(self,event):
self.labelVariable.set(self.addressLink.get()+" (Here is your address!)")
def OnPressDot(self,event):
self.labelVariable.set(self.addressLink.get()+" (Here is your address!!!)")
if __name__=="__main__":
app=Generator(None)
app.title('Converter')
app.mainloop()
#excelRead=open('/Users/BUR/Desktop/listings/data.txt','r')
def exclWrt(typo):
excelWrite.write(typo)
Program runs, but when I press button it gives me:
> Exception in Tkinter callback Traceback (most recent call last):
> File
> "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py",
> line 1470, in __call__
> return self.func(*args) File "/Users/BUR/Documents/Python/Temp+price+keyw.1", line 114, in
> OnButtonClick
> FileRead(link) NameError: global name 'FileRead' is not defined
What did I miss?
You're using a class. First, you'll have an instance of the class passed to every function. Usually it's named self:
class A:
def something(self, my_arguments)
And, to call something from the class, you do this:
def something_else(self, another_arguments):
self.something(another_arguments)
The first argument will automatically be passed. Also, __init__ is called when you create an instance of your class, so you have no need of a separate initialize function.
I suggest you read more about classes here. This is just a very short solution for your problem.
i have written down the code but it gives me an error. It gives the global error and says that it does not define the search. Please help me out guys.
def testSearch():
s = range(0,1000000)
raw_input('basic, -1')
print search(s,-1)
raw_input('binary, -1')
print search1(s,-1)
raw_input('basic, end')
print search(s,1000000)
raw_input('binary, end')
print search1(s,1000000)
s = range(0,10000000)
raw_input('basic, partway')
print search(s,1000000)
raw_input('basic, larger end')
print search(0,10000000)
>>> testSearch()
basic, -1
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
testSearch()
File "C:\Users\bangash\Documents\python files\lec8.py", line 17, in testSearch
print search(s,-1)
NameError: global name 'search' is not defined
So, where is your function search defined? You should define it as a function:
def search(a, b):
...
The function search has to be defined before the code in testSearch has been executed. The code in testSearch is executed when testSearch() is executed. So the following two will work
def search():
pass
def testSearch():
search()
testSearch()
or
def testSearch():
search()
def search():
pass
testSearch()
They both will work because, just before the testSearch() is executed, we got definition for search. But not this
def testSearch():
search()
testSearch()
def search():
pass
I have written a small program that will print all the files and directories inside the path specified by me. The source code is:
import os
import glob
class FolderStats:
targetdir = ""
def __init__(self, dirpath = None):
targetdir = dirpath
totalfiles = 0
totalsubfolders = 0
def FolderIterator(self):
print self.targetdir
listing = os.listdir(self.targetdir)
for infile in listing:
print "current file is: %s" % (infile)
if __name__ == '__main__':
Obj = FolderStats(raw_input('Enter your path: '))
Obj.FolderIterator()
The above code is not executing. I am getting an error in the method FolderIterator: when the print command is executed, it prints nothing. <targetdir> no more contains the path supplied by me. Why is it so?
In your __init__ you need to use self.targetdir instead of targetdir
>>> class Test:
var = 1
def __init__(self):
var = 2
print self.var # Object variable
print var # Local variable
def func(self):
print self.var
print var # this will fail, because there's no local var in this scope
>>> a = Test()
1
2
>>> a.func()
1
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
a.func()
File "<pyshell#10>", line 9, in func
print var
NameError: global name 'var' is not defined