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?
Related
I'm working on a Maya GUI and my main file has a variable that I need in a sub file I'm importing into main.(img_dir) This is from my main file
def do_browse_butt(self, *args):
basicFilter = "All Files (*.*)"
global img_dir
img_dir = cmds.fileDialog2(ff=basicFilter, dialogStyle=2, fm=1)
hold_path = cmds.textField(self.browse_field, edit=1, tx=img_dir[0])
print(img_dir[0])
This is from my sub file
for obj in selected:
shape_node = cmds.listRelatives(obj, shapes=True)
cmds.connectAttr('color_map.outColor', shape_node[0] + '.mtoa_constant_base_color')
cmds.setAttr('color_map.ftn', img_dir[0], typ = 'string')
My main file holds all of my GUI elements and that's where my variable is getting information from. (user input)
I tried making img_dir a global variable hoping that my imported file would be able to access it. But Maya keeps giving me this error so I know it isn't working:
Error: NameError: file C:/Users/hello/Documents/maya/scripts/Custom_OSL_Shader_Amanda_Rabade\texture_file_aiSS.py line 55: name 'img_dir' is not defined #
I came across a similar question and the recommended answer was to create a 3rd file with the desired variable and import it into both current files. But I'm not sure that is going to work with my GUI elements. Does anyone have any suggestions?
I would like a variable to be stored in .py file and be imported into a main Python program.
Let me explain the problem in code. In my home folder I have the following files:
testcode.py
testmodule.py
testcode contains the following code:
import pprint
while __name__ == '__main__':
import testmodule
variableFromFile=testmodule.var
print("Variable from file is "+str(variableFromFile))
print("Enter variable:")
variable=input()
Plik=open('testowymodul.py','w')
Plik.write('var='+variable)
Plik.close()
and testmodule contains:
var=0
Now when I launched testcode.py, and input as variables 1,2,3,4,5 I got the following output:
Variable from file is 0
Enter variable:
1
Variable from file is 0
Enter variable:
2
Variable from file is 0
Enter variable:
3
Variable from file is 0
Enter variable:
4
Variable from file is 0
Enter variable:
5
Variable from file is 0
Enter variable:
But I would like to refresh this variable every time it is printed on screen, so I expect in this line:
print("Variable from file is "+str(variableFromFile))
to update the variable's value. Instead, I get in output only the first value of the variable, so the program print 0 every time. Only restarting the program will refresh the value of var.
Is there a way to import variables from file, change them at runtime and then then use their updated values later on in the script?
I believe your basic problem stems from the use of the variable in the testmodule.py file. As written you code imports this file and thus the pyhton interpreter assigns the value of testmodule.var to the contents thyat exist at load time. The code which attempts to update the variable isn't working the way you intended, since Plik.write('var='+variable) is creating a text string of the form "var = n". Thus subsequent attempts to import the testmodule and get the testmodule.var variable will result in a 0 value.
To fix this problem, as suggested by #JONSG, requires you abandon the import context and do something along the lines of the following:
#Contents of testmodule.txt file
0
#Contents of the testcode.py file
def readVar(fn):
with open(fn, 'r') as f:
return f.read().strip()
def writeVar(fn, val):
with open(fn,'w') as f:
f.write(val)
def runcode():
varfile = 'testmodule.txt' #Assumes testmodule.txt is in same folder as code
variableFromFile= readVar(varfile)
print("Variable from file is "+str(variableFromFile))
variable=input("Enter variable: ")
writeVar(varfile, variable)
def main():
runcode()
if __name__ == "__main__":
main()
Now every time you run the file, the latest variable data will be loaded and then updated with a new value.
I have 2 files prgm.py and test.py
1.prgm.py
def move(self)
H=newtest.myfunction()
i= H.index(z)
user=newuser.my_function()
print(user[i])
How will i get user[i] in the other code named test.py
Use an import statement in the other file;
Like this - from prgm import move
Note: For this to work both of the files needs to be in the same folder or the path to the file you are importing needs to be in your PYTHONPATH
Instead of printing the result, you can simply return it. In the second file, you just import the function from this source file and call it.
Given the situation, move is actually a class method, so you need to import the whole class and instance it in the second file
prgm.py
class Example:
def move(self):
H = newtest.myfunction()
i = H.index(z)
user = newuser.my_function()
return user[i]
test.py
from prgm import Example
example = Example()
user = example.move()
# do things with user
I'm creating a really basic program that simulates a terminal with Python3.6, its name is Prosser(The origin is that "Prosser" sounds like "Processer" and Prosser is a command processer).
A problem that I'm having is with command import, this is, all the commands are stored in a folder called "lib" in the root folder of Prosser and inside it can have folders and files, if a folder is in the "lib" dir it can't be named as folder anymore, its name now is package(But this doesn't care for now).
The interface of the program is just a input writed:
Prosser:/home/pedro/documents/projects/prosser/-!
and the user can type a command before the text, like a normal terminal:
Prosser:/home/pedro/documents/projects/prosser/-! console.write Hello World
let's say that inside the "lib" folder exists one folder called "console" and inside it has a file called "write.py" that has the code:
class exec:
def main(args):
print(args)
As you can see the first 2 lines is like a important structure for command execution: The class "exec" is the main class for the command execution and the def "main" is the main and first function that the terminal will read and execute also pass the arguments that the user defined, after that the command will be responsible to catch any error and do what it will be created to do.
At this moment, everything is ok, but now comes the true help that I need of U guys, the command import.
Like I writed the user can type any command, and in the example above I typed a "console.write Hello World" and exists one folder called "console" and one file "write.py". The point is that the packages can be defined by a "dot", this is:
-! write Hello World
Above I only typed "write" and this says that the file is only inside the "lib" folder, it doesn't has a package to storage and separate it, so it is a Freedom command(A command that doesn't has packages or nodes).
-! console.write Hello World
Now I typed above "console.write" and this says that the file has a package or node to storage and separate it, this means that it is a Tied command(A command that has packages or nodes).
With that, a file is separated from the package(s) with a dot, the more dots you put, more folders will be navigated to find the file and proceed to the next execution.
Code
Finnaly the code. With the import statement I tryied this:
import os
import form
curDir = os.path.dirname(os.path.abspath(__file__)) # Returns the current direrctory open
while __name__ == "__main__":
c = input('Prosser:%s-! ' % (os.getcwd())).split() # Think the user typed "task.kill"
path = c[0].split('.') # Returns a list like: ["task", "kill"]
try:
args = c[1:] # Try get the command arguments
format = form.formater(args) # Just a text formatation like create a new line with "$n"
except:
args = None # If no arguments the args will just turn the None var type
pass
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py"): # If curDir+/lib/task/kill.py exists
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
module.exec.main(args) # Execute the "exec" class and the def "**main**"
else:
pathlast = path[-1] # Get the last item, in this case "kill"
path.remove(path[-1]) # Remove the last item, "kill"
print('Error: Unknow command: ' + '.'.join(path) + '. >>' + pathlast + '<<') # Returns an error message like: "Error: Unknow command: task. >>kill<<"
# Reset the input interface
The problem is that when the line "module = __import__("lib." + '.'.join(path))" is executed the console prints the error:
Traceback (most recent call last):
File "/home/pedro/documents/projects/prosser/main.py", line 18, in <module>
module.exec.main(path) # Execute the "exec" class and the def "**main**"
AttributeError: module 'lib' has no attribute 'exec'
I also tried to use:
module = \_\_import\_\_(curDir + "lib." + '.'.join(path))
But it gets the same error. I think it's lighter for now. I'd like if someone help me or find some replacement of the code. :)
I think you have error here:
You have diffirent path here:
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py")
And another here, you dont have curDir:
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
You should use os.path.join to build paths like this:
module = __import__(os.path.join(curdir, 'lib', path + '.py'))
I have a script called insertPrintCode.py, which works on its own.
I want to call this from another python script using
def main():
execfile("insertPrintCode.py")
def execfile(filename):
exec(compile(open(filename).read(), filename, 'exec'))
This fails inside insertPrintCode.py at the first use of
newSearch = FileSearch()
with
NameError: global name 'FileSearch' is not defined
FileSearch is a class defined inside the same file.