I need help to understand why my python variable is not changing?  Here is the code:  from tkinter import filedialog from tkinter import *  selectedRootFolder = ""  #&lt;-------------------------------------here is the variable declared  # get any folder to be a root folder def add_dir():     root = Tk()     root.withdraw()     dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')     selectedRootFolder = dirname     print("Here: " + selectedRootFolder)#&lt;-----------------------here is the variable changed  # print the root folder  def print_root_dir_path():     print (selectedRootFolder)  #&lt;-----------------------------here is the variable empty -&gt; =""  # in case a wrong number is taken def invalid():     print("---------------------")     print ("INVALID CHOICE!")     print("---------------------")  # exit program def exit_prog():     print ("Thank you, come back soon!")     exit()  # define the menu options menu = {"1":("Choose Directory:", add_dir),     "2":("Print Root Directory Path",print_root_dir_path),     "9":("Exit",exit_prog)    }  while True:         # list the menu     for key in sorted(menu.keys()):         print (key + ":" + menu[key][0])      # pick a number      print("---------------------")     ans = input("Make A Choice: ")     print("---------------------")      #get the number, if none, call invalid function     menu.get(ans,[None,invalid])[1]()   This is just a part of the script, but it should be able to show my problem, which is that when I pick option 1, to choose a directory, it is successful, and it prints the selectedRootFolder, but when I choose option 2 after that, the printed value is just as declared in the beginning, empty.  I do not understand why is that, can u help me?   Thank you.  Edit 1:  Changed:   selectedRootFolder = print(dirname)   To:       selectedRootFolder = dirname print("Here: " + selectedRootFolder)
4613
How can I create or use a global variable in a function?  If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?
120370
I have been teaching myself bash scripting and have run into an issue. I have written a script to take input from the user, using the 'read' command, and make that input a variable to use later in the script. The script works, but....  I would like to be able to get it setup using 'dialog'. I found out that  'dialog --inputbox' will direct the output to 'stderr' and in order to get that input as a variable you have to direct it to a file and then retrieve it. The code I found to explain this is:  #!/bin/bash dialog --inputbox \  "What is your username?" 0 0 2&gt; /tmp/inputbox.tmp.$$  retval=$?  input=`cat /tmp/inputbox.tmp.$$`  rm -f /tmp/inputbox.tmp.$$  case $retval in 0)  echo "Your username is '$input'";; 1)  echo "Cancel pressed.";;  esac   I see that it is sending the sdterr to the /tmp/inputbox.tmp.$$ with 2>, but the output file looks like 'inputbox.tmp.21661'. When I try and cat the file it gives me an error. So I am still unable to get the user input from the --inputbox as a variable.   Example Script:   echo "  What app would you like to remove? "  read dead_app  sudo apt-get remove --purge $dead_app   So as you can see it is a basic script. Is it even possible to get the variable as a word from dialog --inputbox?
115823
Many times when I am watching others code I just want to find where and how a variable is defined. Normally what I do now is look for the type of the variable until I find the definition, that is very time consuming. And I guess that there are some tools that can help me in this rutinary situation. Any suggestion in some tools or commands to help me in this task?.  I know that using a GUI and creating a project this is done automatically I am talking of a way to do this without a GUI. I am working with only text mode. I am running under Linux and I am using C/C++, but suggestions for other languages are welcome.  Thanks a lot.  A possible solution  Michel in one of his comments propose a simple an effective solution define again the variable, in that case in compilation time, the compiler will inform where is the previous definiton. Of course to apply this solution we need to think previously in the locality of the variable.
102253
I'm messing around with python for the first time.  I'm making my own changes to the interface, just because..  How can I move the text inside the buttons down and to the left? The left image is what I have now and the right one it's what I want to do..  Please have in mind that I have zero python knowledge. But I'm willing to learn..
2152
What exactly are the Python scoping rules?  If I have some code:  code1 class Foo:    code2    def spam.....       code3       for code4..:        code5        x()   Where is x found?  Some possible choices include the list below:   In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop   Also there is the context during execution, when the function spam is passed somewhere else. And maybe  pass a bit differently?  There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.
100927
I am not too sure just by reading the manual as to the subtle differences between the .initial and .default PGF key types. Can someone explain and demonstrate the differences with a minimal example?
62995
How do I get a variable's value from one script and import it in another script? But the catch is that the script where I am going to get the variable's value has also some commands that I don't want to run:  Let's say this is script1.sh:  variable="Hello" #some command here e.g. yum check-update   And in script2.sh:  echo $var   I've found an approach where one uses the EXPORT command and puts ./script1.sh inside the script2.sh but it runs the other commands.  So, how can I get the variable's value without running the commands inside it? I hope this question is clear. Thanks in advance!
17041
I have a button in my menu named "New File" as shown:    and I want when I click on the "New File" button to imitate what the Blender File->New does, where a check message box appear first confirming that you want to reload the Start-up File and if pressed then the startup file is loaded as shown below.    This is my script, when I press on new it opens the startup file without checking:  class NewFile(bpy.types.Operator):     """New File"""     bl_idname = "wm.newfile"       bl_label = "New File"     bl_options = {'REGISTER', 'UNDO'}      def execute(self, context):         bpy.ops.wm.read_homefile()         return {"FINISHED"}
117868
The basic idea that I wanted was to create a key to pass a value that would inform \makebox how the contents of the box should be aligned.  Big fail here.    The intended contents of the \makebox are not passed as arguments to \makebox and I seem to have random components of my keys ignored or inserted into the text.  What's happening here?  \documentclass{article} \usepackage{xparse} \ExplSyntaxOn  \tl_new:N  \l_aefl_position_tl \tl_set:Nn \l_aefl_position_tl { [l] }  \keys_define:nn { aefl }     {         pos   .code:n   = {                             \str_case:nnn { #1 }                             {                                 { left   } { \tl_set:Nn \l_aefl_position_tl {[l]} }                                 { center } { \tl_set:Nn \l_aefl_position_tl {}    }                             }                             {                                 { right } { \tl_set:Nn \l_aefl_position_tl {[r]} }                             }                           },     }  \NewDocumentCommand{\aecurrfile}{ o }     {         \group_begin:         \IfNoValueF{#1}{\keys_set:nn { aefl }{#1}}          \makebox[0pt] \l_aefl_position_tl                       { contents ~ of ~ my ~ box }         \group_end:     }  \ExplSyntaxOff \pagestyle{empty} \begin{document}  \begin{tabular}{lcl} unexpected &amp; \verb=[l]=      &amp; \aecurrfile                        \\ unexpected &amp; \verb=[l]=      &amp; Front \aecurrfile[pos=left] Back   \\            &amp;                 &amp; Front \aecurrfile[pos=center] Back \\ unexpected &amp; \verb=right[l]= &amp; Front \aecurrfile[pos=right] Back \end{tabular}  \end{document}   EDIT  Finally, I see why I'm getting the unexpected right in my output.  Argh!
3866
Is it possible to have static class variables or methods in Python? What syntax is required to do this?
29272
The dialog above is created with the code below. When I click on the file icon (see red arrow), nothing happens. Is there a proper way to get these to just work or at least point to a custom operator which invokes context.window_manager.fileselect_add(self) or something similar?  It really seems like the functionality I want should be built into the StringProperty when using FILE_PATH as a subtype... I must be missing something obvious.  What I am trying to do is execute a single operation that requires selecting more than one file path. I can invoke 2 fileselect_add's one after the other, but it becomes confusing because right when you click to accept the path the new path window opens immediately. It is just too confusing as to which one is being selected as there is really no way to customize the fileselect_add window to any usefull degree (as far as I am aware) to make it more obvious what the user is selecting.  Dialog code:  class mydialog(bpy.types.Operator):         bl_idname = "tools.mydialog"         bl_label = "My Dialog"          inFilePath = StringProperty(name="input file", subtype="FILE_PATH")         outFilePrefix = StringProperty(name="out prefix", subtype="FILE_PATH")      def invoke(self, context, event):         return context.window_manager.invoke_props_dialog(self)      def execute(self, context):         print(self.inFilePath)         print(self.outFilePrefix)         return {'FINISHED'}
21860
I'm trying to debug a Python script by placing a print("foo=" + foo) statement in my code.  But where does the output appear?     It doesn't appear on the Python Console, and it doesn't appear on the area that appears when you drag the lower edge of the infobar downwards (what is the name for this area? My script errors show up in red here.)
63383
The code below works flawless, if e.g. triggered by a menu button in a 3D view.          for area in bpy.context.screen.areas:            if area.type == 'VIEW_3D':             for space in area.spaces:                 if space.type == 'VIEW_3D':                      space.viewport_shade = 'BOUNDBOX'   However, if I bundle it into a function and hook it to a handler, it returns a NoneType error:  @persistent def allBound(dummy):   for area in bpy.context.screen.areas:        if area.type == 'VIEW_3D':         for space in area.spaces:             if space.type == 'VIEW_3D':                  space.viewport_shade = 'BOUNDBOX'   bpy.app.handlers.render_pre.append(allBound)   Returns:  AttributeError: 'NoneType' object has no attribute 'areas'   How to solve this?
4318
I was wanting to initialize some strings at the top of my script with variables that have no yet been set, such as:  str1='I went to ${PLACE} and saw ${EVENT}' str2='If you do ${ACTION} you will ${RESULT}'   and then later on PLACE, EVENT, ACTION, and RESULT will be set. I want to then be able to print my strings out with the variables expanded. Is my only option eval? This seems to work:  eval "echo ${str1}"   is this standard? is there a better way to do this? It would be nice to not run eval considering the variables could be anything.
80124
I'd like to change the value of a user-defined project variable (can be manually edited in Project Settings | Variables) using the Python console. I tracked down the  but haven't succeeded in actually changing the variable in the project settings. My code so far:  iface.mapCanvas().mapSettings().expressionContext().scope(0).setVariable('myvar',1)   I guess I'm getting lost in the different expression contexts ...
71146
I have a self made checkbox in a script. Now I want to create a hotkey in the Input manager to toggle it.  What I have done so far is to create a keymap item with wm.context_toggle. But I cannot get the Context Attribute to work. I grab the one from my script, the Python term in the tooltip. Which is WindowManager.deselect_bool and with that I get an error that the "Object has no attribute WindowManager".  What is the proper Context Attribute term here? Is it even possible to do it this way? If not, what is the proper way to assign a toggle hotkey for my custom checkbox?  Script:  import bpy from bpy.props import BoolProperty  class LayoutDemoPanel(bpy.types.Panel):     bl_label = "Demo Panel"     bl_space_type = 'VIEW_3D'     bl_region_type = 'UI'      def draw(self, context):         layout = self.layout          wm = context.window_manager # Our bool is in the windows_manager         layout.prop(wm, "deselect_bool") # Our checkbox  def register():     bpy.types.WindowManager.deselect_bool = bpy.props.BoolProperty(     name="Checkbox", description="A checkbox", default = False)     bpy.utils.register_module(__name__)  def unregister():     del bpy.types.WindowManager.deselect_bool # Unregister our flag when unregister.     bpy.utils.unregister_module(__name__)  if __name__ == "__main__":     register()
51835
Is there a way to assign a value to a variable, that value which we get in terminal by writing any command?  Example command: sensors  From that we get CPU temperature. How can I assign this value to a temp_cpu variable?