how to use local variable to another function in python? - python-2.7

def runscan(self):
p = os.popen('LD_PRELOAD=/usr/libv4l/v4l1compat.so zbarcam
/dev/video0','r')
while True :
code = p.readline().split(':')[1]
print 'Got barcode:', code
def input(self):
self.entryc.insert(END, code)
how about this? i want use local 'code' to the next function to insert the result of barcode to my Tkinter entryBox.. Thanks

just pass it as a parameter. change the definition of input to def input(self, code) and then as the last line of runscan call input(code). A side note, you shouldn't use "input" as the name of a function, because it shadows the built-in input function, which is used for getting user input from the console.

Related

Why is my variable setting itself to " when trying to set to another variable containing a string?

In Theory: When game_start is called and the user inputs 'easy' the variable quiz_paragraph should assume the value of easy_paragprah
In Actuality: The value of quiz_paragraph is set to "
I can verify that user_difficulty is being set properly and is feeding 'easy' properly into set_difficulty. The if statement runs but doesn't alter the value of quiz_paragraph.
Can anyone tell me what I am missing here?
# Easy Paragraph
easy_paragraph = '''\n___1___ is a programming ___2___ used to solve simple and complex problems. ___1___ like
many languages can be used to display a message to a user using ___3___. Try it sometime.
To display this common message by typing ___3___ '___4___ World!' \n'''
# Init Variables
user_difficulty = ""
quiz_paragraph = ""
# Ask user difficulty
def ask_difficulty():
user_difficulty = raw_input("What difficulty level would you like? ")
return user_difficulty
# Difficulty sets returned Paragraph
def set_difficulty(difficulty):
if difficulty == "easy":
quiz_paragraph = easy_paragraph
return quiz_paragraph
else:
print '''Sorry, that is not a valid choice.'''
# Start the game
def game_start():
set_difficulty(ask_difficulty())
print quiz_paragraph
# Game Start Test
game_start()
It looks like you have an issue with scope.
The quiz_paragraph variable within set_difficulty, is not the same as the 'global' quiz_paragraph. Although they currently share the same name, you could rename the one inside set_difficulty to foo and you would have the same result.
You need to set the 'global' quiz_paragraph to the value returned by set_difficulty, or a better another local variable within game_start. That is,
def game_start():
quiz_paragraph = set_difficulty(ask_difficulty())
print quiz_paragraph
or
def game_start():
my_difficulty = set_difficulty(ask_difficulty())
print my_difficulty

chnage value outside of function without returning a value - python

I have an attribute named session that is set to 1. In changeSession() I am trying to change its value to 2. In the last step session is printed and it is still 1. You can see the the code below. Doing the following would make us print the value 2:
session=changeSession()
let changeSession() return the new session value.
However, is it possible to get the value 2 printed without letting changeSession() return anything?
The code:
session=1
def set_session(s):
session=s
def changeSession():
set_session(2)
changeSession()
print session
To do that just use global session in set_session to indicate to python that you want to use the session that you defined outside of the function scope. If you want to document yourself about this behavior, it is called variable scope. Here is the fixed code :
session=1
def set_session(s):
global session
session=s
def changeSession():
set_session(2)
changeSession()
print session

selenium python: what is 'lambda' in webdriverwait.until statements

I'm learning selenium webdriver with python and came across 'lambda' in following line of code. The author did not explain the use of lambda here:
search_button = WebDriverWait(self.driver, 10).until(lambda s:s.find_element_by_name("btnG"))
search_button.click()
I've read about lambda and it says lambda creates functions on the fly and some say its used to return expression. So now I'm confused and not sure exactly what difference does it make here.
In python functions are objects so you can pass them as parameters to other functions. The only thing is if you pass a function with () you call that function at the same time. So it's possible to pass functions which do not take any arguments so it can be called inside the function you passing it to later on. But if you need to pass parameters to the function while you are passing function itself you need to wrap it up in lambda so that it's called only when it's needed.
Edit
To answer the question how it gets s value. If you look into the source here doctoring explains it all:
"""Calls the method provided with the driver as an argument until the
return value is not False."""
Actual code is self explanatory as well:
def until(self, method, message=''):
screen = None
stacktrace = None
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace)

Issue calling another library function using command line argument in Python

I am trying to call different library functions based on the input command-line argument.
My main function would take the input argument and will call the function based on the parameter passed to cli. This is my main function.
from lib.updatefeed import *
def main():
......
......
parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
if args.update:
gather(args.update)
if __name__ == '__main__':
main()
Here, gather() is another function in another python library that I have already imported in the main program.
Here is the body of the imported library with gather() function
def gather(self):
if not os.path.exists('intel'):
os.mkdir('intel')
print "Starting update process"
counter = 0
ioc_list = []
timestr = time.strftime("%Y%m%d-%H%M%S")
for source in IP.iteritems():
print source
name = source + timestr
print name
file = open(name, 'w')
c = connect(source,params=url_param())
for line in c:
if line.startswith("/") or line.startswith('\n') or line.startswith("#"):
pass
else:
file.write(line+'\n')
So my gather() function will be called when the "-update" param is passed to the command line.
The function of gather() function would be to create a directory named "intel".
Then it will iterate through a list of IPs and create file names based on the IP and timestamp. It will then call the connect function to create an HTTP connection to the IP.
It will parse the contents of the IP and write it to the file.
I am not able to achieve this by using my program I have added here.
For some reason, the call from the main() function itself is not succeeding.
I tried adding "print" statements in the gather() function to see what parts are working.
Can the community help me on this please.
The solution to this problem lies in the argument characteristics. By Defining parser.add_argument('-update', type=str, nargs='?', help='Update the local storage') I am asuming that One argument will be passed to the command line along with the -update param.
But I only care about the -update arg to be present in the command line without any additional entity.
This can be overcome by changing the line of script to:
parser.add_argument('-update', action='store_true', help='Update the local storage')
This will ensure that the presence of only -update will call the function 'gather()'.

python function passed into another function as argument

I am new to pragramming and python. This is something like what I have.
Def some_function():
Print "stuff"
Def another_function(x):
running = True
While running:
x
another_function(some_function())
Why does it only print "stuff" the first time going through the loop?
I read some stuff that talked about late binding but not sure if that is what this is or how to fix it in my example.
You didn't pass the function, you called the function and passed its value. So it printed stuff before you ever got into the loop.
To refer to a function without calling it, you leave off the (). So it should be:
another_function(some_function);
Then in another_function, you have to call the function:
def another_function(x):
running = True
while running:
x()