How to pprint to file parameters of an Instance from an AbstractModel in Pyomo? - pyomo

I´m trying to inspect an Instance of an AbstractModel on Pyomo for checking if parameters reading was OK.
For doing so, I´d like to print the parameters values considered in the instance into a txt file.
for doing so, I´ve tried:
for element in instance.component_objects(Param,descend_into=True):
element.pprint(filename=some_filename)
But what I get is that filename is not a valid argument for pprint. Any hints on what could I do?

pprint expects an output stream to write to. Try:
with open('file.txt', 'w') as output_file:
element.pprint(output_file)

Related

Python: unable to produce the output in list format

I want to produce the output in a list format but I am failing.
It's taking some login details from a text file:
Ip1,username1,pwd1
Ip2,username2,pwd2
Ip3,username3,pwd3
Ip4,username4,pwd4
My Python script:
import os.path
save_path = "C:\Users\Public\Pythonlearn"
input_pwd_file= os.path.join(save_path,'loginfile'+'.txt')
with open(input_pwd_file) as f:
list = []
for line in f:
list.append(line)
a=list[3]
print "login details: ",a
I am getting below output:
login details: Ip4,username4,pwd4
But I want it to be like:
login details: ['Ip4','username4','pwd4']
Well, you are just appending the raw line to the list, instead of parsing it. So, it is expected that the lines in the list is exactly the same as the lines in the file. A simple way to parse the line is by using str.split() and do line_as_list = line.split(','). From there it's just a matter of using the list to make a string from.
Final note: Don't call your list variable list. That shadows the built-in constructor to build a list with.
Change a=list[3] to a=list[3].split(',') and as beruic said, don't name your list 'list'

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.

read text file content with python at zapier

I have problems getting the content of a txt-file into a Zapier
object using https://zapier.com/help/code-python/. Here is the code I am
using:
with open('file', 'r') as content_file:
content = content_file.read()
I'd be glad if you could help me with this. Thanks for that!
David here, from the Zapier Platform team.
Your code as written doesn't work because the first argument for the open function is the filepath. There's no file at the path 'file', so you'll get an error. You access the input via the input_data dictionary.
That being said, the input is a url, not a file. You need to use urllib to read that url. I found the answer here.
I've got a working copy of the code like so:
import urllib2 # the lib that handles the url stuff
result = []
data = urllib2.urlopen(input_data['file'])
for line in data: # file lines are iterable
result.append(line) # keep each line, or parse, etc.
return {'lines': result}
The key takeaway is that you need to return a dictionary from the function, so make sure you somehow squish your file into one.
​Let me know if you've got any other questions!
#xavid, did you test this in Zapier?
It fails miserably beacuse urllib2 doesn't exist in the zapier python environment.

How to save lists in python

I have a list including 4000 elements in python which each of its elements is an object of following class with several values.
class Point:
def __init__(self):
self.coords = []
self.IP=[]
self.BW=20
self.status='M'
def __repr__(self):
return str(self.coords)
I do not know how to save this list for future uses.
I have tried to save it by open a file and write() function, but this is not what I want.
I want to save it and import it in next program, like what we do in MATLAB that we can save a variable and import it in future
pickle is a good choice:
import pickle
with open("output.bin", "wb") as output:
pickle.dump(yourList, output)
and symmetric:
import pickle
with open("output.bin", "rb") as data:
yourList = pickle.load(data)
It is a good choice because it is included with the standard library, it can serialize almost any Python object without effort and has a good implementation, although the output is not human readable. Please note that you should use pickle only for your personal scripts, since it will happily load anything it receives, including malicious code: I would not recommend it for production or released projects.
This might be an option:
f = open('foo', 'wb')
np.save(f, my_list)
for loading then use
data = np.load(open('foo'))
if 'b' is not present in 'wb' then the program gives an error:
TypeError: write() argument must be str, not bytes
"b" for binary makes the difference.
Since you say Matlab, numpy should be an option.
f = open('foo', 'w')
np.save(f, my_list)
# later
data = np.load(open('foo'))
Of course, it'll return an array, not a list, but you can coerce it if you really want an array...

How to submit image uploads in Django tests?

The Django docs (http://docs.djangoproject.com/en/dev/topics/testing/#django.test.client.Client.post) say to do this:
>>> c = Client()
>>> f = open('wishlist.doc')
>>> c.post('/customers/wishes/', {'name': 'fred', 'attachment': f})
>>> f.close()
But when I do that the field has the error message "The submitted file is empty." That smells like a PIL issue but the form works fine on the actual site.
Reading the file and sending that instead of just a handle doesn't work either and behaves the same as passing an empty string.
OK I figured it out. I was using the same dummy image for multiple fields and Django doesn't reset the pointer after validating the first field.
Also the example in the docs doesn't show that images need to be opened in binary mode as well.
I think open expects a file path relative to where it’s being called from.
I’m not sure where that would be when a test is being run, but maybe try with an absolute path and see if it works?