I have these two functions:
def check_channel_number(self):
print "***************Channel Checker *********************"
print ''
user_channel_number = int(re.sub('\D', '', raw_input("Enter a channel number, (3digit): "))[:3]);
channel = ("channelNr= '%d'") % (user_channel_number)
print channel
# channel_search = channel + str(user_channel_number)
datafile = file('output.txt')
found = False
for line in datafile:
if channel in line:
found = True
print 'The channel number you entered is correct and will be deleted'
return user_channel_number
print 'The channel number you entered is not on the planner'
return False
and
def delete_events(self):
if user_channel_number == True:
return 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
When I run my script, it says that user_channel_number is not defined globally. How can I use user_channel_number inside the delete_events function?
When you define a variable inside of a function, it is a local variable, meaning that it can only be accessed within that function.
Within a Class
It looks like you're inside a class, so you can make the variable accessible to all methods in the class by defining it like this:
def check_channel_number(self):
self.user_channel_number = ...
And then in your second function, you can use it like the following:
def delete_events(self):
if self.user_channel_number:
Outside of a class
If you aren't using methods inside of a class, you can instead use the global builtin.
For example,
def check_channel_number():
global user_channel_number
user_channel_number = ...
def delete_events():
if user_channel_number:
...
Using a value returned from a function
Instead in your first function, check_channel_number(), you can have it return user_channel_number. You can then call that function inside of delete_events(), like the following:
def check_channel_number():
user_channel_number = ...
return user_channel_number
def delete_events():
if check_channel_number():
...
Functions can not share their local variables. You can return the value from the first and pass it to the second:
def check_channel_number(self):
...
return user_channel_number
def delete_events(self):
user_channel_number = self.check_channel_number()
...
Or save value on the object:
def check_channel_number(self):
...
self.user_channel_number = user_channel_number
...
def delete_events(self):
if self.user_channel_number:
....
So I think when you call the check_channel_number function, user_channel_number is defined in there, so when you call delete_events, it has gone out of scope, maybe something like this would help?
user_channel_number = check_channel_number()
delete_events()
I'd probably have the user_channel_number as an input to the delete function too, so it would turn into this: (where ucn is the user_channel_number)
def delete_events(self, ucn):
if ucn == True:
print 'The program number is correct and will be deleted'
# action = 'DeleteEvent'
menu_action = 'all'
book = 'RECYC:687869882'
arg_list = [('C:\\Users\\yke01\\Documents\\StormTest\\Scripts\\Completed'
'\\Utils\\UPNP_Client_Cmd_Line.py')]
arg_list.append(' --action=')
arg_list.append(action)
arg_list.append(' --ip=')
arg_list.append('10.10.8.89')
arg_list.append(' --objectId=')
arg_list.append(book)
subprocess.call(["python", arg_list])
print 'The program deleted successfully'
I have also changed `return 'The program number is correct and will be deleted'' to a print statement as I have a feeling the return would end the function before the other lines of code would be run
So the code would probably end up being something like:
user_channel_number = check_channel_number()
delete_events(user_channel_number)
EDIT:
just noticed it looks like your functions are part of a class,
in that case, you could do:
self.ucn = self.check_channel_number()
self.delete_events(self.ucn)
(or if you dont want to pass the user_channel_number into the function you could change if user_channel_number: to if self. user_channel_number:
Related
In this code I want to compare the previous message with the current message. So I created a variable to save the previous message. I wanted to create it as a static variable then manipulate it inside the code. but the outside the x function if I declare the variable it shows an error.
flag = 1
previousMessage = "abc"
def x():
do_something
currentMessage = m #got a string from code
if(currentMessage==previousMessage):
#shows error in flag and previousMessgae
#says create parameter of previousMessage and flag
flag=0
return
else:
do_something
previousNews=currentNews
flag=1
return
def call():
while True:
if(flag==1)
x()
time.sleep(60)
elsif(flag==0)
time.sleep(60) **strong text**
call()
Not sure if this is what you need. Try adding global before flag and previousMessage to make that variable a global variable.
How can I print path outside function:
class FirstClas:
path = ''
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(path)
This method don't print anything.
This result:
C:\Python\python.exe C:/Users/JOHN/Desktop/test/tt.py
Process finished with exit code 0
You need to create an instance from the class that you created.
I would suggest doing this:
test = FirstClas()
print(test.num())
Hope this helps
Your method never gets called, and the class variable path is pointless here. Do:
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(FirstClas().num()) # note that this is outside the class!
I don't think you quite understand the purpose of classes, but here's how to make what you have "work" (in the sense that there are no fatal errors):
File global_variable.py
def init_global_variable():
"""initialize variable"""
global GLOBALS_DICT
GLOBALS_DICT = {}
def set_variable(name, value):
"""set variable"""
try:
GLOBALS_DICT[name] = value
return True
except KeyError:
return False
def get_variable(name):
"""get variable"""
try:
return GLOBALS_DICT[name]
except KeyError:
return "Not Found"
init_global_variable() # ADDED.
File tt.py
import os
#import lib.global_variable as glv
import global_variable as glv # Since I don't have your whole package.
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
def imag(self):
icon_file = os.path.join(
glv.get_variable("APP_PATH"),
glv.get_variable("DATA_DIR"),
"paths",
"PathExcel",
)
return icon_file
class Second:
# Put statements in a method so they don't run when the class is defined.
def run(self):
test = FirstClas()
print('first: ' + test.num())
print('second: ' + test.imag())
second = Second()
second.run()
Output:
first: C:\Users\JOHN\Desktop\test.txt
second: Not Found\Not Found\paths\PathExcel
the path does not changed(path = ' ') because you don't run the function num
def move(self):
z = self.comboBox.currentText()
print(z)
Hospital = newtest.my_function()
i = Hospital.index(z)
print('The index of :', i)
user = newuser.my_function()
global (user[i])
print (user[i])
return user[i]
def my_doc():
url = 'https://test.com/steth/get-list'
myobj = {'mongoId': 'user[i]'}
x = requests.post(url, data = myobj)
y=x.json();
print(y)
my_doc()
I need to get user[i] in the second function my_doc.so i made user[i] global.But it is showing syntax error as
global (user[i])
^
SyntaxError: invalid syn
Just get the return of one function, and input it into the other.
class Obj:
def func1(self):
return "something"
# Assuming func2 is inside class.
def func2_class(self, something):
print(something)
# Assuming func2 is outside class.
def func2(something):
print(something)
obj = Obj()
something = obj.func1()
func2(something) # Outside class.
obj.func2(something) # Inside class.
Let's say I have a class like so:
class Shell:
def cat(self, file):
try:
with open(file, 'r') as f:
print f.read()
except IOError:
raise IOError('invalid file location: {}'.format(f))
def echo(self, message):
print message
def ls(self, path):
print os.listdir(path)
In a javascript context, you might be able to do something like "Class"[method_name](), depending on how things were structured. I am looking for something similar in python to make this a "simulated operating system". EG:
import os
def runShell(user_name):
user_input = None
shell = Shell()
while(user_input != 'exit' or user_input != 'quit'):
user_input = raw_input('$'+ user_name + ': ')
...
now, the idea is they can type in something like this...
$crow: cat ../my_text
... and behind the scenes, we get this:
shell.cat('../my_text')
Similarly, I would like to be able to print all method definitions that exist within that class when they type help. EG:
$crow: help\n
> cat (file)
> echo (message)
> ls (path)
is such a thing achievable in python?
You can use the built-in function vars to expose all the members of an object. That's maybe the simplest way to list those for your users. If you're only planning to print to stdout, you could also just call help(shell), which will print your class members along with docstrings and so on. help is really only intended for the interactive interpreter, though, so you'd likely be better off writing your own help-outputter using vars and the __doc__ attribute that's magically added to objects with docstrings. For example:
class Shell(object):
def m(self):
'''Docstring of C#m.'''
return 1
def t(self, a):
'''Docstring of C#t'''
return 2
for name, obj in dict(vars(Shell)).items():
if not name.startswith('__'): #filter builtins
print(name, '::', obj.__doc__)
To pick out and execute a particular method of your object, you can use getattr, which grabs an attribute (if it exists) from an object, by name. For example, to select and run a simple function with no arguments:
fname = raw_input()
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func()
else:
print('That function is not defined.')
Of course you could first tokenize the user input to pass arguments to your function as needed, like for your cat example:
user_input = raw_input().split() # tokenize
fname, *args = user_input #This use of *args syntax is not available prior to Py3
if hasattr(shell, fname):
func = getattr(shell, fname)
result = func(*args) #The *args syntax here is available back to at least 2.6
else:
print('That function is not defined.')
I want to change the function name according to result obtained from another function but the function definition remains same How can i do this i tried the following example but it didn't work
def f(text):
def x(text):
return text+"example"
name=x(text)
def name(y):
return y
return name
p=f("hi ")
print p("hello")
print p.__name__
OUTPUT
hello
name
But i want the function name p.__name__ as "hi example" not name
You can simply assign to __name__:
def f(text):
def r(y):
return y
r.__name__ = text + "example"
return r
p = f("hi ")
print (p("hello")) # Outputs "hello"
print (p.__name__) # Outputs "hi example"
Note that a function name does not have any influence on the function's behavior though, and does not have any meaning except as a part of the string representation or a debugging aid.