How to call a variable from other file in python? - python

I have created 2 files.
a.py has a class foo() and b.py has a class fun(). fun() is a child class of foo().
foo() has a function given below:
def get_random_password(self):
" func to generate random password "
try:
password_characters = string.ascii_letters + string.digits + string.punctuation
nw_password = ''.join(random.choice(password_characters) for i in range(30))
return nw_password
now i want to use this nw_password variable in some other function of fun() ( given below function is used for user login)
username = self.driver.find_element_by_id("username")
time.sleep(3)
username.send_keys(self.vm_spec_dic['name'])
time.sleep(5)
password = self.driver.find_element_by_id("password")
time.sleep(5)
password.send_keys(nw_password)
time.sleep(10)
login = self.driver.find_element_by_id("loginBtn")
login.click()
I am using selenium to automate. I want to call variable nw_password from a.py to b.py. but getting error? I am getting errors like module 'lib.b' has no attribute 'nw_password' ????
from a import nw_password
Importing is not working

The scope of the variable is only inside the function definition, you could probably use a variable and store the return of the get_random_password(self) method
var = yourObjectFromfoo.get_random_password()
then try to import that var

To import your function try this:
from a import get_random_password
If you want to save it to a variable called nw_password you can do this in you main file:
nw_password = get_random_password()
nw_password is just the name of your returned value you're not storing it anywhere. So to get the random password you have to actually run the function you created. And as others have said the variable would be inside the function scope anyway so you would have to make it a global variable (not recommended).

Related

Importing variable from called script repeats the entire calling script

I have a main.py file
import common_functions as conf
print("Main File:")
filename = conf.testing()
from TC import TC
and I want to assign the below return statement as a variable "filename"
common_functions.py
def testing():
print("This should only print once!")
return "awesome file"
I want to then be able to access this variable, in another file that I am importing (TC )
TC.py
from main import filename
print("TC File:")
print(f"Filename is: {filename}")
however, currently, if I do this, then the output is:
Main File:
This should only print once!
Main File:
This should only print once!
TC File:
Filename is: awesome file
I am really struggling with this one, as I am trying to pass a variable into the called scripts, but that variable is only named from another function... so it seems as though everytime I it's called, then the function kicks off again
I would like to be able to set the variable filename in the main file from the function it is calling, and then in the called file (TC.py) I would like to be able to access that variable as a string, not rerun everything.
Is that possible?

How do you access a variable defined by other modules user input?

I am writing a program: prog1 which is importing another module to define a variable.
It works like so:
import modulename1
var1 = attribute1 #situated in modulename1
import modulename2
var2 = attribute2()
function2(var1): # Imagine this being a api call with var1 part of url
#api call
return response.text
function3(function2(var1)+ var2)
modulename1:
attribute1 = input('user value')
modulename2:
def attribute2():
from prog 1 import var 1
atr2 = function(var1) + 'word' #Imagine the function as an api call at
return atr2 #this space
modulename1 accepts user input to define the variable attribute1.
now another module: modulename2 needs to import the var1 with the value from modulename1.
It can´t however import directly from modulename1 as prog 1 is the program launched by the User and importing modulename1 again could result in different user input.
modulename2 in Turn processes var1 and defines attribute2.
var2 is then used in prog1 again. Is there any way to do that?
conditions
Both modules have to be imported completely.
for obvious reasons modulename2 shouldn´t import modulename1

Getting function name and file name through another function

I want python to show me which function has been executed and from what file... so I have the following as test1.py
import sys,os, test2
def some_function():
print (sys._getframe().f_code.co_name +" "+ os.path.basename(__file__) , 'executed')
print (test2.function_details(), 'executed')
test2.py is:
import sys,os
def function_details():
return sys._getframe().f_code.co_name + " " +os.path.basename(__file__)
now when I run it
import test1
test1.some_function()
I get the following output:
('some_function test1.pyc', 'executed')
('function_details test2.pyc', 'executed')
When I try to make a function for calling the file and function of the executed, it tells me the sub function I made instead of the original.
My question is how do I modify test2.py so it will output
('some_function test1.pyc', 'executed')
('some_function test1.pyc', 'executed')
So there are two issues with function_details:
The current frame is function_details so you need to go up one frame to get to the calling frame. To do this you pass 1 to sys._getframe.
__file__ is the name of the current file for whatever module you happen to be in (if defined), this needs to be replaced with the co_filename attribute of the f_code object associated with the correct frame.
Correcting both of these things, we redefine function_details as:
def function_details():
code_obj = sys._getframe(1).f_code
return " ".join([code_obj.co_name, os.path.basename(code_obj.co_filename)])
Which produces the desired result. In my opinion, the inspect module accomplishes this same thing far better than using sys._getframe directly. Here's the new function_details written using inspect:
import inspect
def function_details():
frame = inspect.getouterframes(inspect.currentframe())[1]
return " ".join([frame[3], os.path.basename(frame[1])])

How to set dynamic global variables in Python?

Let's say I've a file a.py and a has a variable var.
In file b.py, I imported, a.py and set a.var = "hello".
Then I imported a.py in c.py and tried to access a.var but I get None.
How to reflect the change in data? It is obvious that two different instances are getting called, but how do I change it?
Edit:
What I am trying to do here is create a config file which constitutes of this:
CONFIG = {
'client_id': 'XX',
'client_secret': 'XX',
'redirect_uri': 'XX'
}
auth_token = ""
auth_url = ""
access_point = ""
Now, let's say I use config.py in the script a.py and set config.access_point = "web"
So, if I import config.py in another file, I want the change to reflect and not return "".
Edit:
Text file seems like an easy way out. I can also use ConfigParser module. But isn't it a bit too much if reading form a file needs to be done in every server request?
As a preliminary, a second import statement, even from another module, does not re-execute code in the source file for the imported module if it has been loaded previously. Instead, importing an already existing module just gives you access to the namespace of that module.
Thus, if you dynamically change variables in your module a, even from code in another module, other modules should in fact see the changed variables.
Consider this test example:
testa.py:
print "Importing module a"
var = ""
testb.py:
import testa
testa.var = "test"
testc.py:
import testa
print testa.var
Now in the python interpreter (or the main script, if you prefer):
>>> import testb
Importing module a
>>> import testc
test
>>>
So you see that the change in var made when importing b is actually seen in c.
I would suspect that your problem lies in whether and in what order your code is actually executed.
In file a.py define a class:
class A:
class_var = False
def __init__(self):
self.object_var = False
Then in b.py import this and instantiate an object of class A:
from a import A
a = A()
Now you can access the attributes of the instance of a.
a.object_var = True
And you can access variables for the class A:
A.class_var = True
If you now check for:
a.class_var
-> True
a.object_var
-> True
another_instance = A()
another_instance.object_var
->False
another_instance.class_var
->True
well , i'd use an text file to set values there,
a.py :
with open("values.txt") as f:
var = f.read()#you can set certain bytes for read
so whenever you import it , it will initialise new value to the var according to the values in the text file , and whenever you want to change the value of var just change the value of the text file

Python variable assigned by an outside module is accessible for printing but not for assignment in the target module

I have two files, one is in the webroot, and another is a bootstrap located one folder above the web root (this is CGI programming by the way).
The index file in the web root imports the bootstrap and assigns a variable to it, then calls a a function to initialize the application. Everything up to here works as expected.
Now, in the bootstrap file I can print the variable, but when I try to assign a value to the variable an error is thrown. If you take away the assignment statement no errors are thrown.
I'm really curious about how the scoping works in this situation. I can print the variable, but I can't asign to it. This is on Python 3.
index.py
# Import modules
import sys
import cgitb;
# Enable error reporting
cgitb.enable()
#cgitb.enable(display=0, logdir="/tmp")
# Add the application root to the include path
sys.path.append('path')
# Include the bootstrap
import bootstrap
bootstrap.VAR = 'testVar'
bootstrap.initialize()
bootstrap.py
def initialize():
print('Content-type: text/html\n\n')
print(VAR)
VAR = 'h'
print(VAR)
Thanks.
Edit: The error message
UnboundLocalError: local variable 'VAR' referenced before assignment
args = ("local variable 'VAR' referenced before assignment",)
with_traceback = <built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0>
try this:
def initialize():
global VAR
print('Content-type: text/html\n\n')
print(VAR)
VAR = 'h'
print(VAR)
Without 'global VAR' python want to use local variable VAR and give you "UnboundLocalError: local variable 'VAR' referenced before assignment"
Don't declare it global, pass it instead and return it if you need to have a new value, like this:
def initialize(a):
print('Content-type: text/html\n\n')
print a
return 'h'
----
import bootstrap
b = bootstrap.initialize('testVar')

Categories

Resources