I've been trying to evaluate a simple "integrate(x,x)" statement from within Python, by following the Sage instructions for importing Sage into Python. Here's my entire script:
#!/usr/bin/env sage -python
from sage.all import *
def main():
integrate(x,x)
pass
main()
When I try to run it from the command line, I get this error thrown:
NameError: global name 'x' is not defined
I've tried adding var(x) into the script, global x, tried replacing integrate(x,x) with sage.integrate(x,x), but I can't seem to get it to work, I always get an error thrown.
The command I'm using is ./sage -python /Applications/path_to/script.py
I can't seem to understand what I'm doing wrong here.
Edit: I have a feeling it has something to do with the way I've "imported" sage. I have my a folder, let's call it folder 1, and inside of folder 1 is the "sage" folder and the "script.py"
I am thinking this because typing "sage." doesn't bring up any autocomplete options.
The name x is not imported by import sage.all. To define a variable x, you need to issue a var statement, like thus
var('x')
integrate(x,x)
or, better,
x = SR.var('x')
integrate(x,x)
the second example does not automagically inject the name x in the global scope, so that you have to explicitly assign it to a variable.
Here's what Sage does (see the file src/sage/all_cmdline.py):
from sage.all import *
from sage.calculus.predefined import x
If you put these lines in your Python file, then integrate(x,x) will work. (In fact, sage.calculus.predefined just defines x using the var function from sage.symbolic.ring; this just calls SR.var, as suggested in the other answer. But if you want to really imitate Sage's initialization process, these two lines are what you need.)
Related
I have the following code:
Script1
def encoder(input_file):
# a bunch of other code
# some more code
# path to output of above code
conv_output_file = os.path.join(input_file_gs, output_format)
subprocess.run(a terminal file conversion runs here)
if __name__ == "__main__":
encoder("path/to/file")
And this is how I try to import and how I set it in script2.
Script2
from script1 import encoder
# some more code and imports
# more code
# Here is where I use the output_location variable to set the input_file variable in script 2
input_file = encoder.conv_output_file
What I am trying to do is use variable output_location in another python3 file. So I can tell script2 where to look for the file that it is trying to process without hardcoding it in.
Every time I run the script though I get the following error:
NameError: name 'conv_output_file' is not defined
What I get from your description is that you want to get a local variable from another python file.
Return it or make it a global variable, and import it.
Maybe you have some difficulty in importing it correctly.
Make these two points clear:
you could only import packages in two ways: the package in PYTHONPATH or the local package. Especially, if you want do any relative import, add . before your package name to specify the package you want to import.
Python interpreter treat a directory as a package only if there is a __init__.py under the directory.
what you actually want to do with the variable conv_output_file? if you just want to get the value/object to which conv_output_file binds, then you better use return statement. or if you want to access the variable and do some more thing on that variable i.e modifying it then you can use global to access the variable conv_output_file.
def encoder(input_file):
# a bunch of other code
# some more code
# path to output of above code
global conv_output_file
conv_output_file = os.path.join(input_file_gs, output_format)
you can access the variable now from 2nd script as firstscript.conv_output_file only after calling that function firstscript.encoder(...) because until the function is not invoked variable does not eists . but it is not recommended to use global, you should avoid the use of global.
I think you want to get that value not access variable so better use return statement
def encoder(input_file):
# a bunch of other code
# some more code
# path to output of above code
return conv_output_file
conv_output_file = os.path.join(input_file_gs, output_format)
return conv_output_file
or simply
return os.path.join(input_file_gs, output_format)
I think apart from not returning the variable or not declaring it as a class variable, you're probably making another mistake.
tell that 2nd script
You have to properly import the 1st script into your second script and use the encoder function as an attribute of the 1st script.
For example, name your first script encoder_script.
In second script,
import encoder_script
encoder_script.encode(filename)
So I've been doing a lot of research and couldn't find a proper answer. I'm quite new to python so sorry if this is a simple question.
So, basically, I'm creating an UI that has a button that should call a function from another .py file. What I did so far is append the file's folder to sys.path and import the .py file as something else. Example, let's say I'm importing myTools.py:
import myTools as mt
Now I can successfully access all functions within myTools via mt.mainFunction() or anything with the mt. prefix.
Now my question:
When I run mt.myFunction() directly it works just fine. Problem is that mainFunction() is another UI that calls different functions at different times. All these functions are on the myTools file.. but Maya won't find them because when they are called within the mainFunction() they don't have the mt prefix.
I mean, I could run those defs on the userSetup.py but it's quite a big code and I wanted to do that the cleanest way :)
Any ideas?
Thanks in advance!
EDIT:
So I just realized is only one function that isn't working. I'm getting this error:
# Error: NameError: file <maya console> line 1: name 'annotationToLocator' is not defined #
Because of that error, I thought that my mainfunction couldn't find any other function on the module.
The actual code where I declare this function:
jobNum = cmds.scriptJob(e=['SelectionChanged', 'annotationToLocator()'])
def annotationToLocator ():
selList = cmds.ls(sl=True)
for item in selList:
if '_ANN' in str(item):
cmds.select(item,d=True)
newItem = str(item).replace('_ANN', '_LOC')
cmds.select(newItem,add=True)
A couple of weird things about this:
1) It works perfectly when I run the code directly.
2) I'm importing the module on the userSetup file.. I'm getting the error above not only when I try to actually run the function that calls this one, but also when Maya starts..
I tried commenting the scriptjob line and now it works just fine, although obviously now I don't have the scriptjob running. I think is some issue with modules and scriptjobs?!
I'm sorry, I know I got off of the original question path here! :)
This sounds like typical python behaviour and should work correctly. Each module has it's own global scope and each function defined in that module will have access to everything defined in that scope.
So in the myTools module each function has access to each other by name, and every function defined in your main module will have access to the mt module object and can get the functions as it's attributes.
You problem stems from using string references to your function. While that works, it only works if they function you're calling by string is in the global python scope -- which usually means it only works in the listener.
The better way to do any maya callbacks is by passing the functions directly to the callback as function objects, not as strings:
import mymodule
cmds.scriptJob(e=('somethingSelected', mymodule.fancyfunction))
Note that mymodule.fancyfunction is passed without parens: you are telling Maya "use this function." If you did it as mymodule.fancyfunction() you'd be telling Maya to use the result of a call to the function , not the function itself.
Suppose we save the following into a Python file called test.py:
x = 14
def print_x():
print x
def increment_x():
x += 1
and then run the following from an interactive Python shell in the same directory:
from test import print_x, increment_x
print_x()
increment_x()
print x
Why does the third call produce an error? Doesn't x need to be defined for the first two to work?
The functions do not throw an error because they still live in the module test, and they still see x in the module test. When you import a reference to a function elsewhere it dose not really move, or become disconnected from its original context. If it did there wouldn't be much use for modules.
The reason why you get a Scope error message is because x is only global in test.py and when you do:
from test import print_x, increment_x
You are not actually importing x to the global scope of the second script.
So, if you want to make x global as well in the second script, do:
from test import *
Try to use the DEBUGGER utility within IDLE to see when x is GLOBAL and when is not
I'm sure this is very simple but I've been unable to get it working correctly. I need to have my main python script call another python script and pass variables from the original script to the script that I've called
So for a simplistic example my first script is,
first.py
x = 5
import second
and my second script is,
second.py
print x
and I would expect it to print x but I get
NameError: name 'x' is not defined
I'm not sure if import is right way to achieve this, but if someone could shed light on it in a simple way that would be great!
thanks,
EDIT
After reading the comments I thought I would expand on my question. Aswin Murugesh answer fixes the import problem I was having, however the solution does not have the desired outcome as I can not seem to pass items in a list this way.
In first.py I have a list which I process as follows
for insert, (list) in enumerate(list, start =1):
'call second.py passing current list item'
I wanted to pass each item in the list to a second python file for further processing (web scraping), I didn't want to do this in first.py as this is meant to be the main 'scan' program which then calls other programs. I hope this now make more sense.
Thanks for the comments thus far.
When you call a script, the calling script can access the namespace of the called script. (In your case, first can access the namespace of second.) However, what you are asking for is the other way around. Your variable is defined in the calling script, and you want the called script to access the caller's namespace.
An answer is already stated in this SO post, in the question itself:
Access namespace of calling module
But I will just explain it here in your context.
To get what you want in your case, start off the called script with the following line:
from __main__ import *
This allows it to access the namespace (all variables and functions) of the caller script.
So now your calling script is, as before:
x=5
import second
and the called script is:
from __main__ import *
print x
This should work fine.
use the following script:
first.py:
x=5
second.py
import first
print first.x
this will print the x value. Always imported script data should be referenced with the script name, like in first.x
To avoid namespace pollution, import the variables you want individually: from __main__ import x, and so on. Otherwise you'll end up with naming conflicts you weren't aware of.
Try use exec
Python3.5:
first.py
x=5
exec(open('second.py').read())
second.py
print(x)
You can also pass x by using:
x=5
myVars = {'x':x}
exec(open('second.py').read(), myVars)
Not sure if this is a good way.
Finally,
I created a package for Python to solve this problem.
Install Guli from PIP.
$ pip install guli
Guli doesn't require installing any additional PIP package.
With the package you can
Guli can be used to pass between different Python scripts, between many processes or at the same script.
pass variables between main Process and another (Multiprocess) Process.
Pass variables between different Python scripts.
Pass variables between 'Main Process' and another (Multiprocess) Process.
Use variables at the same script.
Create / Delete / Edit - GuliVariables.
Example
import guli
import multiprocessing
string = guli.GuliVariable("hello").get()
print(string) # returns empty string ""
def my_function():
''' change the value from another process '''
guli.GuliVariable("hello").setValue(4)
multiprocessing.Process(target=my_function).start()
import time
time.sleep(0.01) # delay after process to catch the update
string = guli.GuliVariable("hello").get()
print(string) # returns "success!!!"
Hope I solved the problem for many people!
Note: Solved. It turned out that I was importing a previous version of the same module.
It is easy to find similar topics on StackOverflow, where someone ran into a NameError. But most of the questions deal with specific modules and the solution is often to update the module.
In my case, I am trying to import a function from a module that I wrote myself. The module is named InfraPy, and it is definitely on sys.path. One particular function (called listToText) in InfraPy returns a NameError, but only when I try to import it into another script. Inside InfraPy, under if __name__=='__main__':, the listToText function works just fine. From InfraPy I can import other functions with no problems. Including from InfraPy import * in my script does not return any errors until I try to use the listToText function.
How can this occur?
How can importing one particular function return a NameError, while importing all the other functions in the same module works fine?
Using python 2.6 on MacOSX 10.6, also encountered the same error running the script on Windows 7, using IronPython 2.6 for .NET 4.0
Thanks.
If there are other details you think would be helpful in solving this, I'd be happy to provide them.
As requested, here is the function definition inside of InfraPy:
def listToText(inputList, folder=None, outputName='list.txt'):
'''
Creates a text file from a list (with each list item on a separate line). May be placed in any given folder, but will otherwise be created in the working directory of the python interpreter.
'''
fname = outputName
if folder != None:
fname = folder+'/'+fname
f = open(fname, 'w')
for file in inputList:
f.write(file+'\n')
f.close()
This function is defined above and outside of if __name__=='__main__':
I've tried moving InfraPy around in relation to the script. The most baffling situation is that when InfraPy is in the same folder as the script, and I import using from InfraPy import listToText, I receive this error: NameError: name listToText is not defined. Again, the other functions import fine, they are all defined outside of if __name__=='__main__': in InfraPy.
This could happen if the module has __all__ defined
Alternatively there could be another version of the module in your path that is getting imported instead of the one you are expecting
Is the NameError about listToText or is it something inside the function causing the exception?
In addition the __all__ variable gnibbler mentioned you could also have a problem with a InfraPy.pyc file lying around somewhere.
I'd recommend putting a import pdb;pdb.set_trace() first in the InfraPy.py file to make sure you are in the right file, and step through the definition of InfraPy.py to see what is happening. If you don't get a breakpoint, you are importing another file than you think.
You can also dir(InfraPy) after importing it, and check which file you are actually importing with InfraPy.__file__.
Can't think of any more import debugging hints right now. ;-)