Considering I have two files - abc.py and xyz.py abc.py contains the following code - li = [1, 2, 3, 4] dt = {'m':1, 'n':4, 'o':9}  I want to read the file abc.py and use the python variables in xyz.py just like how we import using from abc import li, dt. The path to abc.py (say, path/to/abc.py) will be provided and I want to import the contents and use it in xyz.py just like python variables. The following code provides the content in a string format, while I can do some coding and get the job done but I want to generalize and look for a better approach to this. Also note, I find using abc.json a better option but due to some reasons I cannot use it for my purpose. with open(path, &quot;r&quot;) as f:     s = f.read()     print(s)
7325
How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
110447
In Python you can use  for a file-like buffer for character data.  basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ?  The use-case I have is I want to create a ZIP file in memory, and  requires a file-like object.
89893
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?  The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.
90369
Here is the code:  import bpy import csv import sys csv_path = sys.argv[1]  file = open(csv_path) reader = csv.reader(file)  header = next(reader) # 1st line is header  data = [ ] for row in reader:     name0 = row[0]     name1 = row[0]     pathout = 'test-videos/' + row[5] + '.m4v'     s = bpy.context.scene     f = s.objects['FirstName']     f.data.body = name0     f1 = s.objects['FirstName01']     f1.data.body = name1+'?'     bpy.context.scene.render.filepath = pathout     bpy.ops.render.render(animation=True)  bpy.ops.wm.quit_blender()   And here is the error message:  Read blend: /PI-SAT/proj001/proj001-master.blend Traceback (most recent call last): File "/PI-SAT/proj001/proj001master.py", line 9, in &lt;module&gt; header = next(reader) # 1st line is header File"/Applications/Blender/blender.app/Contents/Resources/2.79/python/ lib/python3.5/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 23: invalid continuation byte Error: File format is not supported in file '/PI-SAT/proj001/test.csv' ... opened default scene instead; saving will write to /PISAT/proj001/test.csv   I have read the file with a different script using the exact same code as in lines 2 - 15 and then printing the names and pathout. Running the script from the command line, not from within Blender, it works perfectly.  I have also run the part of the script within the for loop outside of the loop as a script from the command line and it works perfectly.  What am I missing about the CSV file? I created it in Excel on my Mac; is that a problem?
52832
I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:  %config = (     'color' =&gt; 'red',     'numbers' =&gt; [5, 8],     qr/^spam/ =&gt; 'eggs' );   What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.
86547
On my system (Windows Vista Home Premium 64bit) Python files are associated with Python interpreter:  C:\Users\Piotr&gt;assoc .py .py=Python.File C:\Users\Piotr&gt;ftype Python.File Python.File=c:\python\2.7\python.exe "%1" %*   Nevertheless when I run any Python script from command line a window titled Open With pops up asking me to Choose the program you want to use to open this file.
98039
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python and I'm trying to start off with best practices in mind. Basically, I was hoping if anyone could share their experiences, what preferences other developers have and what's the best way to avoid any gotchas down the road?
112416
I import a csv-file via Feeds-module and got stuck with the images for a node. All the other fields are importet as wanted, except the path for the image-field. The images are already uploaded to the directory below...  An example for a row value of a path: sites/all/default/files/images/name.JPG  After the import, the image field is just empty:    Any help would be highly appreciated! Thanks in advance...
97726
When testing the following code:  from osgeo import gdal import json   def read_file(filename):     f = gdal.VSIFOpenL(filename, "rb")     if f is None:         return None     content = gdal.VSIFReadL(1, 10000, f).decode('UTF-8')     gdal.VSIFCloseL(f)     return content   gdal.VectorTranslate('out.json', """{   "type": "FeatureCollection",   "features": [       { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": "coordinates":[[[-188.56933593749997,61.58549218152362],[-173.9794921875,61.58549218152362],[-173.9794921875,66.00015035652659],[-188.56933593749997,66.00015035652659],[-188.56933593749997,61.58549218152362]]] } },   ] }""", format = 'GeoJSON', layerCreationOptions = ['RFC7946=YES', 'WRITE_BBOX=YES'])  got = read_file('/vsimem/out.json') gdal.Unlink('/vsimem/out.json')  print json.loads(got)   from this , the file out.json is empty. The folder is with all permissions for writing allowed. When testing the method gdal.OpenEx, is possible to load an object, but still the method gdal.VectorTranslate returns an empty geojson when trying to pass this new loaded object as a srcDS object. Any hint on solving this issue?
109748
I am a highschool student working at a college's engineering department for the summer. I just began working in blender and have intermediate knowledge of python. Could anyone share a script they've made that can:  1) Read a text file of xyz coordinates into python.  2) Turn these points into some type of curve or path that an object can then follow to model the path the coordinates map out.   Like i said i don't have a great understanding of blender but if someone could write or give me a script that is able to do this it would help. Please explain in simple terms also.. Again I am not an expert.   The file has three points on each line, separated by commmas, and is pretty large. All the coordinates would need to be floats on account that they are decimals.     -4.934860e-06 , -1.380798e-06 , -1.504166e-05 ,  -1.359547e-05 , -4.301138e-06 , -4.403530e-05 ,  -3.727631e-05 , -1.307421e-05 , -1.287422e-04 ,  -7.177810e-05 , -2.724715e-05 , -2.643154e-04 ,    here are some of the data points when in the text file  now with the .csv they were put into an excel file   when copied and pasted they look like this:  -4.93E-06   -1.38E-06   -1.50E-05
4990
I am looking for a way to access a .mxd file's layer names and data sources.  In ArcGIS Desktop, I could do:  def print_layer_info(mxd_path):     print(mxd_path + ":")     mxd = arcpy.mapping.MapDocument(mxd_path)      for df in arcpy.mapping.ListDataFrames(mxd, "*"):         lyr = arcpy.mapping.ListLayers(mxd, "", df)[0]         if lyr.supports("dataSource"):             print "\t" + lyr.name             print "\t\t" + lyr.dataSource     del mxd   According to , I could do:  p = arcpy.mp.ArcGISProject("file.mxd")   But that doesn't work. When I do that I get a OSError.  Since the arcpy.mapping.MapDocument is gone in ArcPy for ArcGIS Pro, what is the equivalent way of reading layer name and datasource of an .mxd file?
94844
I have a file1.txt  USA Joe 123.123.123 Russia Marry 458.786.892 Canada Greg 151.844.165 Latvia Grace 125.895.688   and file2.txt  1 123.123.123 2 151.844.165 3 465.879.515   and I want to create a new file result.txt where I print my only those lines that adresses (xxx.xxx.xxx) are both  in file1 and file2 so my result should be  USA Joe 123.123.123 Canada Greg 151.844.165   I need to use awk, but how I need to use it for both files?
6086
Putting aside whether the use of , I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:  from __future__ import with_statement import pickle  # Simple class definition class myclass(object):     def __init__(self, data):         self.data = data  # Create an instance of the class x = myclass(100)  # Pickle the instance to a file with open("c:\\pickletest.dat", "wb") as f:     pickle.dump(x, f)  # Replace class with exact same definition class myclass(object):     def __init__(self, data):         self.data = data  # Read an object from the pickled file with open("c:\\pickletest.dat", "rb") as f:     x2 = pickle.load(f)  # The class names appear to match print x.__class__ print x2.__class__  # Uh oh, this fails...(why?) assert isinstance(x2, x.__class__)   Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.
58840
I have a model that passes a variable to a python script. The script uses that variable to query some directories and return a list of paths. What I want to know is:    How can I then use each of those paths as the parameter in a subsequent operation? Is the bridge between python and ModelBuilder a one-way street?
98249
While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.  The C++ code looks something like this:  #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt;  using namespace boost::python;  int main(int, char **)  {     Py_Initialize();      try      {         object module((handle&lt;&gt;(borrowed(PyImport_AddModule("__main__")))));          object name_space = module.attr("__dict__");         object ignored = exec("from myModule import MyFunc\n"                           "MyFunc(\"some_arg\")\n",                           name_space);          std::string res = extract&lt;std::string&gt;(name_space["result"]);     }      catch (error_already_set)      {         PyErr_Print();     }      Py_Finalize();     return 0; }   A (very) simplified version of the Python code looks like this:  import thirdparty  def MyFunc(some_arg):     result = thirdparty.go()     print result   Now the problem is this:  'MyFunc' executes fine, i can see the print of 'result'. What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace. I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.
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!
111951
The idea would be to use it as... a pipe in a command. For instance: say there's some kind of long path which has to be retyped again and again, followed by a pipe and a second program, i.e.  "directory1/directory2/direcotry3/file.dat | less -I "   I'd like that part to be stored in a variable, so it could be used like this:  r="directory1/directory2/direcotry3 \| less -I -p " $ cat path1/path2/$r &lt;searchterm&gt;   Instead, I get  cat: invalid option -- I Try `cat --help' for more information.   ... meaning the pipe clearly didn't work.