Dynamically importing files in Python - python

I wish to be able to import a file in Python whose source is a text file that will be often modified.
In other words, let's suppose that I have a file name, dados.py whose content in a given moment is:
x=[2, 3, 7, 9]
(and this is the only line of the file (possible?))
and my main program has the line
import dados
What I want is that when the import is made I will have an array with the values seen above.
But, if the values of the file dados.py change, the next time that the main program runs it will work with the new values.
The thing is that I don't know if I can have a line of code with variables and if python will recognize that it must execute this line.
The question I am trying to explain in details is because I had a working program with the x=[2, 3, 7, 9] writen on the source code. The moment that I replaced that line by:
import dados
line, python complains with a message like
File "testinclude.py", line 15, in <module>
print(x)
NameError: name 'x' is not defined

Your variable is defined within a module, so you must namespace the variable
import dados
print(dados.x)
Or you can import x from dados
Alternative solution would be to use some JSON or other configuration file, then read and load it. It's not clear why you need a Python file only to define variables

In this instance it is probably better to use a file instead of a python module. However, if you insist on using a module, you can store the data in a variable and access it using the "." operator.

Related

When I import an array from another file, do I take just the data from it or need to "build" the array with how the original file build it?

Sorry if the question is not well formulated, will reformulated if necessary.
I have a file with an array that I filled with data from an online json db, I imported this array to another file to use its data.
#file1
response = urlopen(url1)
a=[]
data = json.loads(response.read())
for i in range(len(data)):
a.append(data[i]['name'])
i+=1
#file2
from file1 import a
'''do something with "a"'''
Does importing the array means I'm filling the array each time I call it in file2?
If that is the case, what can I do to just keep the data from the array without "building" it each time I call it?
If you saved a to a file, then read a -- you will not need to rebuild a -- you can just open it. For example, here's one way to open a text file and get the text from the file:
# set a variable to be the open file
OpenFile = open(file_path, "r")
# set a variable to be everything read from the file, then you can act on that variable
file_guts = OpenFile.read()
From the Python docs on the Modules section - link - you can read:
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it
This means that importing a module has the same behavior as running it as a regular Python script, unless you use the __name__ as mentioned right after this quotation.
Also, if you think about it, you are opening something, reading from it, and then doing some operations. How can you be sure that the content you are now reading from is the same as the one you had read the first time?

How to extract all variable and their value from a python script with location like "C:\\Users\\SomeFolder\\PythonFile.py"?

I am working on a text editor made with python and i want to add a feature of Variable Explorer in my editor I am not able to extract the variable values from a python file. My basic working principle is that my program takes location of the current edited file and try to import it but I am not able to import because that is string not an object. It is bit confusing so let me show the code.
fileName='C:\Users\Project.py'
class varExplorer:
def ShowVarList(editfile):
editfile.replace('\','.')
editfile.replace('.py','')
editfile.replace(':','')
# so the file path will be like C.Users.Project
import editfile # the problem
print(editfile.__dict__)# here i will get dictionary of values
varExplorer.ShowVarList(fileName)
help taken for dict
print(editfile.__dict__)
from
I want to extract all the variable names with a python script, from a python file, without editing the python file
The main problem is that it cannot import from a string
import editfile # the problem
because it is a string and import does not take strings
So I want a function which can print all the variable and their values from a specific python file from any location.
Use importlib
import importlib
importlib.import_module(editfile)
Also be careful, str is immutable in Python, replace returns a new string and does not modify its argument.
So you get:
import importlib
class VarExplorer:
def show_var_list(editfile):
editfile = editfile.replace('\\','.')
editfile = editfile.replace('.py','')
editfile = editfile.replace(':','')
# so the file path will be like C.Users.Project
module = importlib.import_module(editfile) # the solution
print(vars(module))

Python 3 use a code from a file

I have two Python files. In my main file I work with a openpyxl module. In my second file I have many string lines with concatenating using Excel file cells, for example:
'/ip address=' + sheet['D'+ row].value + '\n'
and many others. But there is a problem, if I import that file to a main file using:
from file2 import *
I get many errors about undefined names like:
NameError: name 'sheet' is not defined
And it is really defined only in my main file, like:
wb = openpyxl.load_workbook(filename='clients.xlsx')
sheet = wb.get_sheet_by_name('Page1')
How can I import everything from my file2 and get it work?
As far as I can wrap my head around it, import only imports functions. execfile(*path*) should work for you in your case.
There are some more ways to import python into python, which you might want to check out.

How do you take a function from an excel spreadsheet and run it with python?

Hello whoever is reading this.
I am having trouble taking a python function from an excel spreadsheet and then running it in python.
I'd like to stress on the fact that I actually defined my function in python, and it's not an excel function.
Please note that this is my second time questioning and have only ever done coding as a hobby.
Here is an example of what I want to take:
heal(2,c)
I am using xlrd to analyze data on the spreadsheet.
Here is a chunk from my code.
e = worksheet.cell(rowidx,colidx+1)
f = str(e).replace("'","")
g = f.replace("text:","")
This chunk focuses on converting the 'cell object' to a 'string' and making it look like the function required.
The end result is this:
g = heal(2,c)
My problem is that I cannot seem to activate this function.
I have also tried doing "g()" but it came up with the error message:
File "C:\Users\Alexander\Dropbox\Documents\Python\Hearthstone\Hearthstone.py", line 18, in play
g()
TypeError: 'str' object is not callable
I do not mind if you tell me a way to activate "g" or just directly run it from the spreadsheet.
Please let me know if you need any more information.
Thank you for you time.
You can use eval for same. Here, I am considering that funciton is defined in current file only.
Example:
eval('heal(2,c)')
If function is defined in other file i.e. "file",import it and call using:
Example:
import file
eval('file.heal(2,c)')

How to use .format with variables in loop with QGIS/Python

I've got the following code, but I can't quite get it to work:
import glob
import os
import processing # for QGIS functionality
os.chdir("/home/mydir/vector")
columnid = ['SAMP300','SAMP100','SAMP30', 'SAMP10']
for x in glob.glob("prefix*.shp"):
for y in columnid:
for z in [1, 2, 3]:
output_alg0='"/home/mydir/vector/samples/{x}_{y}_{z}.shp"'.format(x=x.rstrip('.shp'), y=y, z=z)
output_0='processing.runalg("qgis:randompointsinsidepolygonsvariable","/home/mydir/vector/{x}",0,"{y}",1000,output_alg0)'.format(x=x, y=y)
The script reads through a directory of .shp files, and uses variables to name the outputs. output_alg0 creates the output file name used in the next step. The file name is based on the original file, and two variables within the loop. output_0 is the actual QGIS algorithm that is run, which references each .shp file in the loop, passes the columnid variable and some fixed parameters, and references output_alg0 for naming the output .shp file.
If I append print in front of the two commands within the loop, I get the output that I'm expecting (i.e., the {x},{y}, and {z} variables are correctly populated. Furthermore, the script gives no error when executed, but no output is produced.
Here's an example of the output by appending print and parentheses to the two lines within the loop:
output_alg0="/home/mydir/vector/samples/prefix_SAMP10_3.shp"
output_0=processing.runalg("qgis:randompointsinsidepolygonsvariable","/home/mydir/vector/prefix.shp",0,"SAMP10",1000,output_alg0)
I can copy and paste both lines exactly as they appear above into the QGIS Python Console and the commands are executed as expected (i.e., random point file is generated based on the input shapefile, and an output shapefile is created as specified).
I think it has something to do with how I'm using .format and/or perhaps how I'm using single and/or double quotations, and/or some sort of Python/QGIS interaction that I don't quite understand.
EDIT: Instead of using the two output_ prefixes, I also tried out this one-liner version, and the script executes (without error), but no output is created.
import glob
import os
import processing # for QGIS functionality
os.chdir("/home/mydir/vector")
columnid = ['SAMP300','SAMP100','SAMP30', 'SAMP10']
for x in glob.glob("prefix*.shp"):
for y in columnid:
for z in [1, 2, 3]:
'processing.runalg("qgis:randompointsinsidepolygonsvariable","/home/mydir/vector/{w}",0,"{y}",1000,"/home/mydir/vectorsamples/{x}_{y}_{z}.shp")'.format(w=x, x=x.rstrip('.shp'), y=y, z=z)
Currently your loop is generating the variables how you want them to and assigning them to output_alg0 and output_0 the way you want, but you don't ever DO anything with them after that.
I've asked for your expected output in a comment. If you add that we can probably figure out how to get you there. My GUESS is that you're trying to execute output_0 (which currently is just a string that looks like a python command). In which case you'd have to use exec(output_0) but be wary of using exec in general. It's a scary command.
EDIT:
If I were you, I'd do something more like:
# inside your loops::
output_alg0='"/home/mydir/vector/samples/{x}_{y}_{z}.shp"'.format(x=x.rstrip('.shp'), y=y, z=z)
output_0 = processing.runalg("qgis:randompointsinsidepolygonsvariable", "/home/mydir/vector/{x}".format(x=x), 0, y, 1000, output_alg0)
That way you're running the script directly rather than writing a bit of code then executing it.
Changed my EDIT-ed line written as:
'processing.runalg("qgis:randompointsinsidepolygonsvariable","/home/mydir/vector/{w}",0,"{y}",1000,"/home/mydir/vectorsamples/{x}_{y}_{z}.shp")'.format(w=x, x=x.rstrip('.shp'), y=y, z=z)
to this, which wraps exec with quotations marks around the line above:
exec('processing.runalg("qgis:randompointsinsidepolygonsvariable","/home/mydir/vector/{w}",0,"{y}",1000,"/home/mydir/vectorsamples/{x}_{y}_{z}.shp")'.format(w=x, x=x.rstrip('.shp'), y=y, z=z))
The above modification to the script is running and iterates through the list of .shp files within the specified directory; however, I don't think this is the most kosher answer possible. I'll hold off accepting my own answer if something better and/or more QGIS-friendly comes along.
PS-thanks to #Adam Smith for pointing out exec

Categories

Resources