how to assign a value to global variable in runtime in python - python-2.7

While running a code in python I want to update a dictionary value that is in config(global variable) I'm trying to do but i got the following error.
config.py
survey={'url':''}
runnigcode.py
url=config.__getattribute__(config.environment)
url['url']='myurl.com'
TypeError: "'module' object does not support item assignment"

in your runningcode.py, just import the variable as a method:
from config import survey
print survey
if you want to modify the value in the config.py, just use write method, like in this post: Edit configuration file through python

Related

Python 'rawpy._rawpy.RawPy' object has no attribute 'imread' after second pass

I try to process a series of DNG raw picture files and it all works well for the first pass (first fils). When I try to read the second DNG file during the second pass through the for-next loop, I receive the error message 'rawpy._rawpy.RawPy' object has no attribute 'imread' when executing the line "with raw.imread(file) as raw:".
import numpy as np
import rawpy as raw
import pyexiv2
from scipy import stats
for file in list:
metadata = pyexiv2.ImageMetadata(file)
metadata.read()
with raw.imread(file) as raw:
rgb16 = raw.postprocess(gamma=(1,1), no_auto_bright=True, output_bps=16)
avgR=stats.describe(np.ravel(rgb16[:,:,0]))[2]
avgG=stats.describe(np.ravel(rgb16[:,:,1]))[2]
avgB=stats.describe(np.ravel(rgb16[:,:,2]))[2]
print i,file,'T=', metadata['Exif.PentaxDng.Temperature'].raw_value,'C',avgR,avgG,avgB
i+=1
I tried already to close the raw object but from googling I understand that is not necessary when a context manager is used.
Help or suggestions are very welcome.
Thanks in advance.
You're overwriting your alias of the rawpy module (raw) with the image you're reading. That means you'll get an error on the second pass through the loop.
import rawpy as raw # here's the first thing named "raw"
#...
for file in list:
#...
with raw.imread(file) as raw: # here's the second
#...
Pick a different name for one of the variables and your code should work.

SolverFactory.solve summary option

Pyomo solver invocation can be achieved by command line usage or from a Python script.
How does the command line call with the summary flag
pyomo solve model.py input.dat --solver=glpk --summary
translate to e.g. the usage of a SolverFactory class in a Python script?
Specifically, in the following example, how can one specify a summary option? Is it an (undocumented?) argument to SolverFactory.solve?
from pyomo.opt import SolverFactory
import pyomo.environ
from model import model
opt = SolverFactory('glpk')
instance = model.create_instance('input.dat')
results = opt.solve(instance)
The --summary option is specific to the pyomo command. It is not a solver option. I believe all it really does is execute the line
pyomo.environ.display(instance)
after the solve, which you can easily add to your script. A more direct way of querying the solution is just to access the value of model variables or the objective by "evaluating" them. E.g.,
instance.some_objective()
instance.some_variable()
instance.some_indexed_variable[0]()
or
pyomo.environ.value(instance.some_objective)
pyomo.environ.value(instance.some_variable)
pyomo.environ.value(instance.some_indexed_variable)
I prefer the former, but the latter is more appropriate if you are accessing the values of immutable, indexed Param objects. Also, note that variables have a .value attribute that you can access directly (and update if you want to provide a warmstart).
Per default the --summary command option stores a 'result' file in json format into the directory of your model.
You can achieve the same result by adding the following to your code:
results = opt.solve(instance, load_solutions=True)
results.write(filename='results.json', format='json')
or:
results = opt.solve(instance)
instance.solutions.store_to(results)
results.write(filename='results.json', format='json')

Fetching data using Psycopg2 module in python

While I am trying to run the following basic python script for fetching data in postgresql database using psycopg2 module :
cur.execute("""SELECT project from project_tlb""")
rows=cur.fetchall()
print rows[5]
the output for above I am getting is
('html',)
The value inside the table is html which is of type 'text'. Any suggestions how to get only the value html instead of ('html',) ?
The returned value ('html',) is a tuple so you can just access its first element:
rows[5][0]
to get
'html'

Get value in a post request, Django

am getting the following post data in my django app
POST
Variable Value
csrfmiddlewaretoken u'LHM3nkrrrrrrrrrrrrrrrrrrrrrrrrrdd'
id u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null'
am trying to get the id value in variable id i.e "id":4 (the value 4). When I do request.POST.get('id')I get the whole json string. u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null' How can I get the "id" in the string?
The data you are sending is simply a json string.
You have to parse that string before you can access data within it. For this you can use Python's json module (it should be available if you're using Python 2.7).
import json
data = json.loads( request.POST.get('id') )
id = data["id"]
If you somehow don't have the json module, you can get the simplejson module.
For more details, refer this question : best way to deal with JSON in django
That's happening because id is string, not dict as it should be. Please provide your template and view code to find source of problem.

Global name 'number' is not defined on module import

I'm using python 2.7 on linux machine and I'm sure this is an obvious question but
I really need this answer.
Module one named one in file test
def one():
number=1
Module two named two in file exam
def two():
if number == 1:
print "apples and oranges"
and both of them imported into a container named modi.py like this
import test, exam
test.one()
exam.two()
I was hoping to set the variable "number" in module one and reference it in module two but I keep getting the name error "global name 'number' is not defined"
I just can't see the problem
This is because number is in test.py. Try adding global number before the first use in test.py and import test in exam.py. Then use if test.number == 1: