Fix Python – What shebang to use for Python scripts run under a pyenv virtualenv

When a Python script is supposed to be run from a pyenv virtualenv, what is the correct shebang for the file?
As an example test case, the default Python on my system (OS X) does not have pandas installed. The pyenv virtualenv venv_name does. I tried getting the path of the Python executable from the virtualenv.
pyenv activate venv_name
which pyth….

Fix Python – Securely storing environment variables in GAE with app.yaml

I need to store API keys and other sensitive information in app.yaml as environment variables for deployment on GAE. The issue with this is that if I push app.yaml to GitHub, this information becomes public (not good). I don’t want to store the info in a datastore as it does not suit the project. Rather, I’d like to swap out the values from a file….

Fix Python – How do you send a HEAD HTTP request in Python 2?

What I’m trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know o….

Fix Python – Returning boolean if set is empty

I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function
I take the intersection of two sets, and want to return True or False based on if the resulting set is empty.
def myfunc(a,b):
c = a.intersection(b)
#…return boolean here

My initial thought was to do
return c is not None

H….

Fix Python – Download and save PDF file with Python requests module

I am trying to download a PDF file from a website and save it to disk. My attempts either fail with encoding errors or result in blank PDFs.
In [1]: import requests

In [2]: url = ‘http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf’

In [3]: response = requests.get(url)

In [4]: with open(‘/tmp/metadata.pdf’, ‘wb’) as f:
…: f…..

Fix Python – What is a good way to handle exceptions when trying to read a file in python?

I want to read a .csv file in python.

I don’t know if the file exists.
My current solution is below. It feels sloppy to me because the two separate exception tests are awkwardly juxtaposed.

Is there a prettier way to do it?
import csv
fName = “aFile.csv”

try:
with open(fName, ‘r’) as f:
reader = csv.reader(f)
for row in ….

Fix Python – How can I copy a Python string?

I do this:
a = ‘hello’

And now I just want an independent copy of a:
import copy

b = str(a)
c = a[:]
d = a + ”
e = copy.copy(a)

map( id, [ a,b,c,d,e ] )

Out[3]:
[4365576160, 4365576160, 4365576160, 4365576160, 4365576160]

Why do they all have the same memory address and how can I get a copy of a?
….