text
stringlengths 226
34.5k
|
---|
Python matplotlib: Showing the same figure after plotting progressively more graphs
Question: I want to do something like this, where the figure is the same.
fig = plt.figure()
plt.plot(x1,y1)
plt.show()
So it'll show a point in figure 1 at x1, y1
Then if I do a mouse click or press a key, something along the lines of:
plt.plot(x2,y2)
plt.show()
But the figure window shouldn't close, it should just plot a new point on top
of it.
I want to do this kinda thing for a math presentation, I know its not even
necessary at all but I had this thought and wondered if it was possible for
python. I have done MATLAB in the past and stuff like this is so much easier.
Answer: The simplest way is to do this is to enable "interactive mode" in matplotlib,
which draws automatically on changes. This is a good way to do thing in the
command-line, and is equivalent to how MATLAB does it. However, it is slower,
so it is better not to use it in scripts, so it is not the default:
import matplotlib.pyplot as plt
x1 = 1
x2 = 2
y1 = 1
y2 = 4
plt.ion() # turn on interactive mode
plt.figure()
plt.xlim(0, 10) # set the limits so they don't change while plotting
plt.ylim(0, 10)
plt.hold(True) # turn hold on
plt.plot(x1, y1, 'b.')
input() # wait for user to press "enter", raw_input() on python 2.x
plt.plot(x2, y2, 'b.')
plt.hold(False) # turn hold off
For a loop, it would work like this:
import matplotlib.pyplot as plt
import numpy as np
xs = np.arange(10)
ys = np.arange(10)**2
plt.ion()
plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 100)
plt.hold(True)
for x, y in zip(xs, ys):
plt.plot(x, y, 'b.')
input()
plt.hold(False)
If you use IPython, however, you can just use `%pylab`, which takes care of
importing everything and enabling interactive mode:
%pylab
xs = arange(10)
ys = arange(10)**2
figure()
xlim(0, 10) # set the limits so they don't change while plotting
ylim(0, 100)
hold(True)
for x, y in zip(xs, ys):
plot(x, y, 'b.')
input() # raw_input() on python 2.x
hold(False)
|
Is there a way to minimize a window in Windows 7 via Python 3?
Question: I am running a program with a built-in Python interpreter. Periodically I want
that program to be able to go "full screen" or be minimized.
This will be running on Windows 7.
I am wondering if there is a way to do this in Python (so that I could call
the function from my program). Using only standard libraries would be ideal
but if there is a way to do this with an external module, that would be fine
too.
Thanks.
Answer: To minimize a window you need to know either the title of the window, or its
window class. The window class is useful when the exact window title is not
known. For example the following script shows two different ways to minimize
the Microsoft Windows Notepad application assuming:
import ctypes
notepad_handle = ctypes.windll.user32.FindWindowW(None, "Untitled - Notepad")
ctypes.windll.user32.ShowWindow(notepad_handle, 6)
notepad_handle = ctypes.windll.user32.FindWindowW(u"Notepad", None)
ctypes.windll.user32.ShowWindow(notepad_handle, 6)
To determine the class name to use, you would need to use an tool such as
Microsoft's Spy++. Obviously if Notepad was opened with a file, it would have
a different title such as `test.txt - Notepad`. If this was the case, the
first example would now fail to find the window, but the second example would
still work.
If two copies of notepad were running, then only one would be closed. If all
copies needed to be closed, you would need to enumerate all windows which
requires more code.
The [ShowWindow](https://msdn.microsoft.com/en-
us/library/windows/desktop/ms633548%28v=vs.85%29.aspx) command can also be
used to restore the Window.
|
Use bool list to retrieve elements from another list - Python
Question: I have this situation:
main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]
What I want to do is, extract elements from `main_list` according to the
boolean value in `get_indices`. I tried the following but it is not working :
result = main_list[bool(get_indices)]
print result
10
It should be `12, 30, 10`
Answer: I just came across `compress()` which is best suited for this task.
`compress()` generates an iterator for efficient looping.
from itertools import compress
main_list = [12, 10, 30, 10, 11,10, 31]
get_indices = [1, 0, 1, 1, 0, 0, 0]
print list(compress(main_list, get_indices))
[12, 30, 10]
|
ProgressBar with Threading in Python and Kivy
Question: I have following code
**main.py**
class ExampleRoot(BoxLayout):
def any(self,*args):
x=0
while x<10:
server.sendmail(c,g,e)
total_emails="activity done"
#### progressbar not updating in live time
self.ids["pb"].value+=1
from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
PythonActivity.toastError(total_emails)
x+=1
this is my kv file
<ExampleRoot>:
ProgressBar:
id:pb
max:10
value:0
progress bar is not updating in real time...when loop ends it suddenly
increases progress bar....
is it possible to update scrollbar in realtime using thread?
Answer: The reason your progressbar does not update until the end is because you are
tieing up the MainThread with your loop. All Kivy GUI updates are done from
the main thread, so if you block it, nothing in the GUI will update.
You can solve this two ways. If the content of your loop executes fast, you
can just use Kivy's [Clock](http://kivy.org/docs/api-kivy.clock.html) object
to run your function instead of looping:
def any(self, x, *args):
server.sendmail(c,g,e)
total_emails="activity done"
self.ids["pb"].value+=1
from jnius import autoclass
PythonActivity = autoclass('org.renpy.android.PythonActivity')
PythonActivity.toastError(total_emails)
x+=1
if x < 10:
Clock.schedule_once(lambda dt: self.any(x))
If your "sendmail" takes a while, it will still freeze the GUI while it is
working. You can put this in a background thread, but you must remember to not
modify GUI elements from a background thread, as GUIs are not threadsafe. You
can again use `Clock.schedule_once` to schedule a function that updates the
progress bar.
|
how to improve efficiency of this Python code
Question: I have written a simple code in ABAQUS PDE to export results to csv files. I
put a part of it here and I am wondering how I may improve its efficiency.
I am so appreciated for your valuable comments.
from odbAccess import *
from abaqusConstants import *
outputname='job-23.odb'
odb=openOdb(outputname)
myAssembly=odb.rootAssembly
% Defining number of elements
nofl=46
s1=open('s1.csv','w')
%Defining lenght of steps
lengthsteps=len(odb.steps.keys())
for j in range(nofl):
for i in range(lengthsteps-1):
step=odb.steps.keys()[i]
s=odb.steps[step]
jj=odb.steps[opstep].historyRegions.keys()[j]
sdata=s.historyRegions[jj].historyOutputs['S11'].data
l=len(sdata)
for k in range(l-1):
s1.write('%10.4E\n' % sdata[k][1])
s1.close()
Answer: Something which you should **not** use in python is:
objectNr = len(myObjects)
for i in range(objectNr-1):
a = myObjects[i]
print a
Something like this would be better:
for myObject in myObjects:
print myObject
In your case would it be maybe easier, when you iter over odb.steps.
for step in odb.steps:
s=odb.steps[step]
...
Much shorter better to read and it is the python way.
|
python plot intersection of line and data
Question: I have a data file that looks something like this:
0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35
And I would like to find the the value that intersects with a slope. My code
looks like this so far:
from numpy import *
from pylab import *
data = loadtxt('test.dat')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plot(strain, stress)
plot(x, y)
show()
Answer: You can use the `interp1d` function from scipy to create a linear
interpolation between each set of points. `interp1d` takes x and y values and
returns a function that takes an x value and returns the corresponding y
value. Once you have a function for stress and for y, you need to figure out
where those intersect. One way to do this efficiently is with something like
the bisection method, which finds zeros.
Here's the code: import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import bisect
data = '''0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35'''
data = [line.split() for line in data.split('\n')]
data = np.array(data, dtype = 'float')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
#use interp1d to get interpolated points
y = interp1d(x, y)
stress = interp1d(strain, stress)
#set starting points
x1 = max(x[0], strain[0])
x2 = min(x[-1], strain[-1])
max_err = .01
#create function
f = lambda x : stress(x) - y(x)
#find x1 where f(x1) = 0
x1 = bisect(f, x1, x2, xtol = .001)
y1 = stress(x1)
plt.figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plt.plot(strain, stress(strain))
plt.plot(x, y(x))
plt.scatter(x1, y1)
plt.show()
And the resulting image:[](http://i.stack.imgur.com/DmJRB.png)
|
File I/O in Python
Question: I'm attempting to read a CSV file and then write the read CSV into another CSV
file.
Here is my code so far:
import csv
with open ("mastertable.csv") as file:
for row in file:
print row
with open("table.csv", "w") as f:
f.write(file)
I eventually want to read a CSV file write to a new CSV with appended data.
I get this error when I try to run it.
Traceback (most recent call last):
File "readlines.py", line 8, in <module>
f.write(file)
TypeError: expected a character buffer object
From what I understood it seems that I have to close the file, but I thought
with automatically closed it?
I'm not sure why I can write a string to text but I can't simply write a CSV
to another CSV almost like just making a copy by iterating over it.
Answer: To read in a CSV and write to a different one, you might do something like
this:
with open("table.csv", "w") as f:
with open ("mastertable.csv") as file:
for row in file:
f.write(row)
But I would only do that if the rows needed to be edited while transcribed.
For the described use case, you can simply copy it with
[shutil](https://docs.python.org/2/library/shutil.html) before hand then
opening it to append to it. This method will be much faster, not to mention
far more readable.
The `with` operator will handle file closing for you, and will close the file
when you leave that block of code (given by the indentation level)
|
lLoad fixture in django migrations using loaddata
Question: My django application needs data to work properly, so in certain migration I
loaded data using the recommended method by almost all stack overflow answers:
from django.core.management import call_command
def load_fixture(apps, schema_editor):
call_command('loaddata', 'fixture_name', app_label='my_app')
class Migration(migrations.Migration):
...
operations = [
migrations.RunPython(load_fixture),
]
In the following migration, I deleted a field and added another field. So far
so good.
Now I want to test my application, but when the test database is being
created, the 'call_command' above fails because the fixtures don't specify
values for the field created in the next migration. I suspect this is because
`call_command` isn't loading the objects on the test database but on
`settings.DATABASES['default']`.
How should I load fixtures in a migration so that I can build test databases?
Answer: For tests, I know you can load in fixtures within Djangos TestCase, see
[django
docs](https://docs.djangoproject.com/en/1.7/topics/testing/tools/#django.test.TransactionTestCase.fixtures)
For production, The approach you are taking using `loaddata` seems viable, but
you would need to make sure your fixtures are kept up to date (as youve
highlighted), as fixture inserting is quite forceful, an alternative is to
create your models using the ORM inside of a `RunPython` operation, this can
help to give them more flexibility..
There is a [feature request](https://code.djangoproject.com/ticket/24778) in
Django for something more `official`, though I'm not sure if its being
considered or not, but it would only add convenience for fixture loading, not
a way to make fixtures dynamic..
[this other stack overflow
post](http://stackoverflow.com/questions/25960850/loading-initial-data-with-
django-1-7-and-data-migrations/25981899#25981899) contains some other
interesting approaches
Hope that's in some way helpful
|
Python Nesting Modules
Question: I have spent a lot of time researching this and still cannot understand why I
keep getting ImportErrors: No module named ...
My file structure is as follows:
/Package
/mode
__init__.py
moduletoimport.py
/test
__init__.py
abc.py
File `moduletoimport.py` contains:
class ClassToImport(object):
def test(self):
return True
File `abc.py` contains the following code:
from mode.moduletoimport import ClassToImport
From the terminal I type:
python abc.py
The aim here is to import a module that is up the directory.
Answer: ## Quick Fix
A quick fix to this problem is, in the file `abc.py` add the following to the
top of the file:
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
**However, this is really not that correct.** I have some serious questions
about the way you're structuring your project and believe the below section
will help greatly.
## Better Solution
In general, if you're designing a module to be imported, you want your project
structure to look something like this:
package_name/
/* setup.py and other misc files */
package_name/
__init__.py
/* module files go here */
test/
/* tests go here */
The top level `package_name/` is really just for holding the project. It will
contain your `setup.py`, possibly configuration things etc.
Underneath the top level, we have another directory called `package_name`.
This is where all your actual python code will go.
Also underneath the top level, we have another directory called `test`. This
is where all the tests should go. I would strongly consider using
[nose](https://nose.readthedocs.org/en/latest/) to test your python
application.
## Example
Let's build a quick example of what you are trying to accomplish. The final
product will have the following structure/files:
my_project/
my_project/
__init__.py
my_class.py
test/
test_my_class.py
The contents of `my_class.py` are:
class MyClass(object):
def test(self):
return True
The contents of `test_my_class.py` are:
import unittest
from my_project.my_class import MyClass
class TestMyClass(unittest.TestCase):
def test_my_class(self):
c = MyClass()
self.assertEqual(c.test(), True)
Now, if you [install nose](https://nose.readthedocs.org/en/latest/) you should
be able to (from the top level of your project) run `nosetests`.
There are tons of tutorials out there for how to do this. But for brevity's
sake, I'll let you do some searching on your own.
Hope this helps.
|
Issue Setting Up Django Database Access API Using SQLite
Question: I just started using Django, and I am going through the documentation
[here](https://docs.djangoproject.com/en/1.8/intro/tutorial01/) to build my
first app, but I am running into some kind of issue related to the database
access API for SQLite.
My directory structure looks like this:
[](http://i.stack.imgur.com/AI1Fu.png)
The only files I have edited are `models.py` and `settings.py` and it is all
code from the documentation.
models.py:
from django.db import models
class Question(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
# ...
def __str__(self): # __unicode__ on Python 2
return self.choice_text
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
The only changes I have made to `settings.py` are adding my timezone
`TIME_ZONE = 'US/Pacific'` and adding `'polls',` to `INSTALLED_APPS`.
(For full disclosure, I have set up my `urls.py` just to test hello world,
which is not part of the documentation, but I don't think that's causing the
issue. Here's the code for that if it's relevant.)
urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.debug import default_urlconf
from django.http import HttpResponse
def hello(request):
return HttpResponse('Hello world!!!')
urlpatterns = patterns('',
# Examples:
url(r'^$', hello),
# url(r'^blog/', include('blog.urls')),
#url(r'^admin/', include(admin.site.urls)),
#url(r'^$', default_urlconf),
)
Now, the issue I'm running into is when I get to the "Playing with the API"
section. When I open a `python manage.py shell` for the second time in that
section, I'm supposed to be able to use the command `Question.objects.all()`
and get the result `[<Question: What's up?>]` with "What's up?" being the
value of `question_text`. The problem is I'm still getting the result
`[<Question: Question object>]` instead of the `question_text` value.
I've gone back and re-created my app three times in the hope that I missed
something during the setup, but I get the same issue every time and I seem to
be following the documentation exactly. Am I missing something here?
Answer: First, make sure that the contents of `models.py` match with what's given in
the tutorial
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self): # __str__ on Python 3
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200, default="")
votes = models.IntegerField(default=0)
def __unicode__(self): # __str__ on Python 3
return self.choice_text
Also make sure that the migrations are up to date.
If you're running python 2, use `__unicode__` else use `__str__`.
That should solve the problem for you.
|
Python - Delete the last line of a txt file while appending it
Question: I would like to specify a raw_input command to delete the last line of the txt
file while appending the txt file.
Simple code:
while True:
userInput = raw_input("Data > ")
DB = open('Database.txt', 'a')
if userInput == "Undo":
""Delete last line command here""
else:
DB.write(userInput)
DB.close()
Answer: You can't open a file in append mode and read from it / modify the previous
lines in the file. You'll have to do something like this:
import os
def peek(f):
off = f.tell()
byte = f.read(1)
f.seek(off, os.SEEK_SET)
return byte
with open("database.txt", "r+") as DB:
# Go to the end of file.
DB.seek(0, 2)
while True:
action = raw_input("Data > ")
if action == "undo":
# Skip over the very last "\n" because it's the end of the last action.
DB.seek(-2, os.SEEK_END)
# Go backwards through the file to find the last "\n".
while peek(DB) != "\n":
DB.seek(-1, os.SEEK_CUR)
# Remove the last entry from the store.
DB.seek(1, os.SEEK_CUR)
DB.truncate()
else:
# Add the action as a new entry.
DB.write(action + "\n")
EDIT: Thanks to Steve Jessop for suggesting doing a backwards search through
the file rather than storing the file state and serialising it.
You should note that this code is **very** racy if you have more than one of
this process running (since writes to the file while seeking backwards will
break the file). However, it should be noted that you can't really fix this
(because the act of removing the last line in a file is a fundamentally racy
thing to do).
|
Portable python package to other platform?
Question: Suppose I have a Windows machine A, the python package x is installed and used
in script.py as:
#this is in script.py
import x
x.useit()
Then I can execute script.py in machine A like:
python script.py
Now if I copy script.py to a Mac machine B, is there a way to run script.py
without install the package x there?
Answer: the only way i think it works is using some modules like py2exe, py2app ...
when u importing modules u are calling some functions and classes... so u need
them for running them in program. maybe there is hard way that u can copy the
module in your program(the lines u need at least..!) but i think its little
dumb! and i didn't try before!
so hopefully py2app is ready to use and i think py2app will work for sure !
|
For file in directories, rename file to directoryname
Question: I have let's say 5 directories, let's call them dir1, dir2, dir3, dir4, dir5.
These are all in the current directory. Each of them contains 1 files called
title.mkv. I want to rename the files to the directory name they are in, ie
the file title.mkv in dir1, I want to rename to dir1.mkv.
I also want to then move the file to another folder. What python tools do I
need for this besides os and glob?
Answer: If you have the full filename and directory, to rename the files, you can use
import os
f_name = 'E:/temp/nuke.mkv'
# Removes '/' at the end of string
while f_name.endswith('/'):
f_name = f_name[:-1]
# Generates List Containing Directories and File Name
f_name_split = f_name.split('/')
f_path = ''
# Iterates Through f_name_split, adding directories to new_f_path
for i in range(len(f_name_split)-1):
f_path += f_name_split[i] + '/'
# Makes New Name Based On Folder Name
new_name = f_name_split[-2] + '.mkv'
# Gets The Old File Name
f_name = f_name_split[-1]
# Renames The File
os.rename(f_path + f_name, f_path + new_name)
To go through all of the directories, you could do it recursively, have the
system output it to a file [windows: dir /s /b /a > file.txt], or use os.walk.
To move a file, you can use os.rename(source, destination)
|
How to send shortcut keys in the current web browser?
Question: I am trying to send some shortcut keys to open a new tab in chrome, using
selenium in python. I open up facebook, then I log in, then I want to open a
new tab where I can pass the url of one of my friend so that I can view his
profile. I wrote the following code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import getpass
driver = webdriver.Chrome()
#opening browser and loging into the account
def login():
driver.get("http://www.facebook.com")
elem = driver.find_element_by_xpath("//*[@id=\"email\"]")
elem.send_keys("myUsername")
password = driver.find_element_by_name("pass")
password.send_keys("myPassword")
elem.send_keys(Keys.RETURN)
driver.implicitly_wait(5)
def scout():
scroll = driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.get("http://www.facebook.com/some.friend")
driver.implicitly_wait(8)
login()
scout()
But it gives me the error:
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
I made the browser wait implicitly but still it's unable to find the tag.
Please help.
Answer: First of all, try calling `WebDriverWait` instead of
`find_element_by_css_selector` in order to find elements. It calls
`find_element_by_<method>` every half a second until given timeout. That way
you don't have to gamble with `implicitly_wait` or `time.sleep()`. Regarding
your open new tab problem - you cannot send ctrl + t to chromedriver, it
simply wouldn't do anything (it would work on firefox though). I've
encountered this problem before, and the best solution I found is to search
for a link in the website itself, so if you're on Facebook you can use that F
icon at the top left. Then you can send ctrl + shift + click to open that in a
new tab.
from selenium.webdriver import ActionChains
actions = ActionChains(driver);
actions.move_to_element(link)
actions.send_keys(Keys.CONTROL+ Keys.SHIFT)
actions.click(link)
actions.perform()
From there you should just switch tabs using
tabs = driver.window_handles
driver.switch_to.window(tabs[<index>])
|
ImportError: No module named ceph_argparse
Question: I'am trying to run `ceph` command but I get the error
$ ceph
Traceback (most recent call last):
File "/usr/local/bin/ceph", line 100, in <module>
from ceph_argparse import \
ImportError: No module named ceph_argparse
I found this link <http://tracker.ceph.com/issues/11388>
But `/dist-packages/ceph_argparse.py` doesn't exit in my `/usr/lib/python2.7`
I working on CentOS7 and I install `ceph` by
./autogen.sh
./configure
make
make install
and follow this link <http://ceph.com/docs/master/install/manual-deployment/>
Answer: Need to get all of require package before install ceph
following this link >> <http://ceph.com/docs/master/install/get-packages/>
|
Python Pandas filtering and creating new dataframe
Question: I am filtering a list for those records that contain a key word in one column.
The overall list, outputs is given as:
outputs =
sent_name Name Lat Lng type
Abbey Road Station, London, UK Abbey Road, London E15, UK 51.53193 0.00376 [u'transit_station', u'point_of_interest', u'establishment']
Abbey Wood Station, London, UK Abbey Wood, London SE2, UK 51.49106 0.12142 [u'transit_station', u'point_of_interest', u'establishment']
I search output[3] for the string 'station' and then append the results where
this is true to an empty list, results. As per -
results = []
for output in outputs:
if "station" in output[3]:
results.append(output)
I wish to use Pandas for future analysis but do not know how to recreate a
DataFrame after filtering these results.
OD = pd.read_csv('./results.csv', header=0)
Where, results.csv is again:
sent_name Name Lat Lng type
Abbey Road Station, London, UK Abbey Road, London E15, UK 51.53193 0.00376 [u'transit_station', u'point_of_interest', u'establishment']
Abbey Wood Station, London, UK Abbey Wood, London SE2, UK 51.49106 0.12142 [u'transit_station', u'point_of_interest', u'establishment']
Using iterrows, I am able to iterate over the rows in the pandas dataframe and
filter out those where 'station' exists in the type column.
for index, row in OD.iterrows():
if "station" in row['type']:
However, I have not been able to create a new DataFrame from this. My ultimate
aim is to create a new csv (that only contains records that feature 'station'
in the type column) using the .to_csv function in Pandas.
I have tried to create a new dataframe with appropriate index names. Then
filtering as above and attempting to append these results to the new dataframe
OD_filtered = pd.DataFrame(index=['sent_name','Name','Lat', 'Lng', 'type'])
for index, row in OD.iterrows():
if "station" in row['type']:
OD_filtered.append([row['sent_name'], row['Name'], row['Lat'], row['Lng'], row['type']])
pprint(OD_filtered)
However, this fails to write to dataframe and it remains empty. When I
print(OD_filtered) it gives:
Empty DataFrame
Columns: []
Index: [sent_name, Name, Lat, Lng, type]
Answer: You can create a boolean mask by calling `apply` on 'type' column to create
your new df:
In [37]:
import io
import pandas as pd
t="""sent_name;Name;Lat;Lng;type
Abbey Road Station, London, UK;Abbey Road, London E15, UK;51.53193;0.00376;[u'transit_station', u'point_of_interest', u'establishment']
Abbey Wood Station, London, UK;Abbey Wood, London SE2, UK;51.49106;0.12142;[u'transit_station', u'point_of_interest', u'establishment']"""
df = pd.read_csv(io.StringIO(t), sep=';')
df
Out[37]:
sent_name Name Lat \
0 Abbey Road Station, London, UK Abbey Road, London E15, UK 51.53193
1 Abbey Wood Station, London, UK Abbey Wood, London SE2, UK 51.49106
Lng type
0 0.00376 [u'transit_station', u'point_of_interest', u'e...
1 0.12142 [u'transit_station', u'point_of_interest', u'e...
In [39]:
# filter the df
df[df['type'].apply(lambda x: 'station' in x)]
Out[39]:
sent_name Name Lat \
0 Abbey Road Station, London, UK Abbey Road, London E15, UK 51.53193
1 Abbey Wood Station, London, UK Abbey Wood, London SE2, UK 51.49106
Lng type
0 0.00376 [u'transit_station', u'point_of_interest', u'e...
1 0.12142 [u'transit_station', u'point_of_interest', u'e...
So in your case the following should work:
new_df = OD[OD['type'].apply(lambda x: 'station' in x)]
|
Extract specific string from Telnet output with Python
Question: I'm trying to write a Python script to telnet to a bunch of Cisco routers,
extract the running configuration and save it. Each router has a different
name so what I would like to do is to extract the device name and save the
output file with that name. For example this a snippet of a Cisco router
output where there is a line **"hostname ESW1"** :
Current configuration : 1543 bytes
!
version 12.4
service timestamps debug datetime msec
service timestamps log datetime msec
no service password-encryption
!
hostname ESW1
!
boot-start-marker
boot-end-marker
!
I'm using telnetlib and I can get the output and save it in a variable. My
question is how can I identify that specific line and extract the "ESW1"
string after the "hostname "?
Answer: A simple way is to use regular expressions and search for the hostname in your
variable. To match the hostname you could use this regex pattern:
`hostname (?P<hostname>\w+)`
The code in python would look like:
import re
p = re.compile(ur'hostname (?P<hostname>\w+)')
test_str = u"Current configuration : 1543 bytes\n\n!\nversion 12.4\nservice timestamps debug datetime msec\nservice timestamps log datetime msec\nno service password-encryption\n!\nhostname ESW1\n!\nboot-start-marker\nboot-end-marker\n!"
hostnames = re.findall(p, test_str)
print(hostnames[0])
The result is: `ESW1`
Try it out on [regex101](https://regex101.com/r/nX9qB7/1)
|
Quick Python method to get neighbouring elements in 2D grid
Question: Is there a method somewhere in a Python package that returns the elements and/
or indexes of an element in a 2d grid. E.g. if we have:
[[1, 2, 3, 4],
[5, 6, 7, 8],
[7, 8, 9, 0]]
..and we give the method the index `[0,1]` it should return `[1, 6, 3]` (if it
could return `[[0,0], [1,1], [0,2]]` that would be even better) and giving it
`[1,1]` would return `[5, 2, 8, 7]` (or the corresponding indexes- order isn't
important).
There is obviously the simple solution to this, however, it's too slow since I
want to do this on a large scale for arrays with several thousand elements.
Any suggestions? Thanks in advance.
Answer: Why is it too slow?
From the input coordinate [a, b] return the list [[a-1, b], [a+1, b], [a,
b-1], [a, b+1]], avoiding coordinates outside your grid.
|
python datetime.astimezone behavior incorrect?
Question: Here is the code which first parses time from string in IST and then converts
that to UTC. So when it 4:00 pm in India the time in GMT / UTC is 10:30 am.
While the following code prints it as 9:30 pm. So instead of subtracting the
offset it is adding the offset. From the python documentation
<https://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone>
the sample implementation of astimezone, it does appear that it would add the
offset if it is negative but it seems contrary to what it should do. The
documentation says that it adjusts the time such that UTC time remains same
but in passed timezone's local time which is contrary to the sample
implementation.
from dateutil.parser import parse
from pytz import timezone
d = parse('Tue Sep 01 2015 16:00:00 GMT+0530')
# Prints datetime.datetime(2015, 9, 1, 16, 0, tzinfo=tzoffset(None, -19800))
print d
utc = timezone('UTC')
# Prints datetime.datetime(2015, 9, 1, 21, 30, tzinfo=<UTC>)
print d.astimezone(utc)
I am not sure what is wrong. Is it the implementation of the astimezone or the
documentation or the offset itself has its sign reversed?
Answer: `astimezone()` is correct. `parse()` is incorrect or the input is ambiguous.
`parse()` interprets `GMT+0530` as being the deprecated POSIX-style `GMT+h`
timezone format where the utc offset sign is reversed. See [Timezone offset
sign reversed by Python dateutil?](http://stackoverflow.com/q/31078749/4279)
To fix it, use the opposite sign:
>>> from dateutil.parser import parse
>>> d = parse('Tue Sep 01 2015 16:00:00 GMT+0530')
>>> utc = d.replace(tzinfo=None) + d.utcoffset() #NOTE: the opposite sign
>>> utc
datetime.datetime(2015, 9, 1, 10, 30)
If the input may be unambiguous (when `parse()` returns correct results) then
you should not change the utc offset sign by hand. You could strip the
timezone and reapply it again instead:
>>> import pytz
>>> tz = pytz.timezone('Asia/Kolkata')
>>> tz.localize(parse('Tue Sep 01 2015 16:00:00 GMT+0530').replace(tzinfo=None), is_dst=None)
datetime.datetime(2015, 9, 1, 16, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>)
>>> _.astimezone(pytz.utc)
datetime.datetime(2015, 9, 1, 10, 30, tzinfo=<UTC>)
It may fail for ambiguous or non-existent times (during DST transitions). If
you know the input is in `GMT+h` format then use the 1st code example and
convert to UTC manually instead.
|
Change localtime from UTC to UTC + 2 in python
Question: How I can change this code from localtime UTC to UTC+2. Now `hours()` function
print 13 but I need to write 15.
import time;
def hours():
localtime = time.localtime(time.time())
return localtime.tm_hour
def minutes():
localtime = time.localtime(time.time())
return localtime.tm_min
def seconds():
localtime = time.localtime(time.time())
return localtime.tm_sec
print(hours())
#minutes()
#seconds()
Answer: You can use pytz along with datetime modules. for a timezone reference i'd
look [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones). I'd
do something of this sort:
import datetime
import pytz
utc_dt = datetime.datetime.now(tz=pytz.utc)
amsterdam_tz = pytz.timezone("Europe/Amsterdam")
local_amsterdam_time = amsterdam_tz.normalize(utc_dt)
print local_amsterdam_time.hour
print local_amsterdam_time.minute
print local_amsterdam_time.second
|
How to extract correct data from Sqlite database using Python?
Question: I have a database of people names and their birthdays. The format of birthday
is `mm/dd/yyyy`, like "3/13/1960".
I want to extract a list of people who are born after a specific date. I
called this date "base".
The program that you see below, firstly creates a DB of people (to simulate
the real DB that I want to work with), and then extracts the required list.
The problem is that the result is not as I expect:
import datetime as dt
import peewee as pw
db = pw.SqliteDatabase('people1.db')
class Person(pw.Model):
name = pw.CharField()
birthday = pw.DateField(formats=['%m/%d/%Y'])
class Meta:
database = db # This model uses the "people.db" database.
db.create_tables([Person])
bob0 = Person(name='Bob0', birthday='4/13/1940')
bob1 = Person(name='Bob1', birthday='5/13/1950')
bob2 = Person(name='Bob2', birthday='3/13/1960')
bob3 = Person(name='Bob3', birthday='3/13/1970')
bob4 = Person(name='Bob4', birthday='3/13/1980')
bob5 = Person(name='Bob5', birthday='3/13/1990')
base = Person(name="base", birthday='3/13/1960')
bob0.save()
bob1.save()
bob2.save()
bob3.save()
bob4.save()
bob5.save()
base.save()
for item in Person.select().where(Person.birthday > base.birthday):
print item.name , item.birthday
Output:
>>> ================================ RESTART ================================
>>>
Bob0 1940-04-13
Bob1 1950-05-13
Bob3 1970-03-13
Bob4 1980-03-13
Bob5 1990-03-13
>>>
As you see above, base = `3/13/1960`. So I shouldn't have _Bob0_ and _Bob1_ in
output! How can I handle it?
_Note that, I don't want to change the format of birthdays in the database. I
also don't want to fetch all the rows and check them later! I want to fetch
the required rows only._
Answer: SQlite stores date-times as strings. So as other have suggested in comments
and other [answers](http://stackoverflow.com/a/1933735/248296) you should use
a different format for storing dates, so that "date ordering and lexical
ordering work out the same":
import datetime as dt
import peewee as pw
db = pw.SqliteDatabase('people1.db')
class Person(pw.Model):
name = pw.CharField()
birthday = pw.DateField(formats=['%Y-%m-%d'])
class Meta:
database = db # This model uses the "people.db" database.
db.create_tables([Person])
Person.create(name='Bob0', birthday=dt.date(1940, 4, 13))
Person.create(name='Bob1', birthday=dt.date(1950, 5, 13))
Person.create(name='Bob2', birthday=dt.date(1960, 3, 13))
Person.create(name='Bob3', birthday=dt.date(1970, 3, 13))
Person.create(name='Bob4', birthday=dt.date(1980, 3, 13))
Person.create(name='Bob5', birthday=dt.date(1990, 3, 13))
base = Person.create(name="base", birthday=dt.date(1960, 3, 13))
for item in Person.select().where(Person.birthday > base.birthday):
print item.name , item.birthday
This gives:
Bob3 1970-03-13
Bob4 1980-03-13
Bob5 1990-03-13
**UPDATE**
I haven't noticed your comment that you don't want to change the database.
Here is a crazy way to extract parts of the date:
SELECT
birthday,
CAST(substr(birthday, 1, instr(birthday, '/') - 1) AS integer),
CAST(substr(substr(birthday, instr(birthday, '/') + 1), 1, instr(substr(birthday, instr(birthday, '/') + 1), '/') - 1) AS integer),
CAST(substr(birthday, instr(birthday, '/') + instr(substr(birthday, instr(birthday, '/') + 1), '/') + 1) AS integer)
FROM person
which on my test data gives:
4/13/1940 4 13 1940
12/13/1950 12 13 1950
3/3/1960 3 3 1960
3/25/1970 3 25 1970
3/13/1980 3 13 1980
3/13/1990 3 13 1990
3/13/1960 3 13 1960
You can use these expressions to compare them with parts of the given date:
query = """
SELECT *
FROM person
WHERE
(
substr('0000' || CAST(substr(birthday, instr(birthday, '/') + instr(substr(birthday, instr(birthday, '/') + 1), '/') + 1) AS integer), -4, 4) || '-' || -- year
substr('00' || CAST(substr(birthday, 1, instr(birthday, '/') - 1) AS integer), -2, 2) || '-' || -- month
substr('00' || CAST(substr(substr(birthday, instr(birthday, '/') + 1), 1, instr(substr(birthday, instr(birthday, '/') + 1), '/') - 1) AS integer), -2, 2) -- day
) > '1960-03-03'
"""
for item in Person.raw(query):
print item.name, item.birthday
I am reconstructing ISO date here and use it for comparison.
|
How to check if a specific port is listening using Python script?
Question: I want to check if api and app are running before running tests on them. I
know I can get a list of open ports in CLI using
`sudo lsof -iTCP -sTCP:LISTEN -n -P`
But I want to write a python script to do so. Any ideas on what library should
I use or how should I do that?
Answer: I found a port checker using socket
[here](http://code.activestate.com/recipes/577769-tcp-port-checker/) and it
works.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import re
import sys
def check_server(address, port):
# Create a TCP socket
s = socket.socket()
print "Attempting to connect to %s on port %s" % (address, port)
try:
s.connect((address, port))
print "Connected to %s on port %s" % (address, port)
return True
except socket.error, e:
print "Connection to %s on port %s failed: %s" % (address, port, e)
return False
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-a", "--address", dest="address", default='localhost', help="ADDRESS for server", metavar="ADDRESS")
parser.add_option("-p", "--port", dest="port", type="int", default=80, help="PORT for server", metavar="PORT")
(options, args) = parser.parse_args()
print 'options: %s, args: %s' % (options, args)
check = check_server(options.address, options.port)
print 'check_server returned %s' % check
sys.exit(not check)
|
What is the right way to manage namespaces in Python 3?
Question: Most of my programming background is in C++ and Java, but for professional
reasons I'm starting to learn Python. One of the first things that I noticed
was Python's new approach to packages and namespaces, but after googling
around for awhile and doing some experimenting I thought I started to get the
hang of it.
Then I read [this](http://python-
notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html),
which indicated that everything I had just learned was wrong. So now I'm
confused again, and I'm having trouble figuring out how I should organize my
code.
* * *
Here's a very concrete question which I don't really know how to answer
correctly for any version of Python, and in particular I don't know if the
answer changed from Python 2 to 3. Let's say I want a class in a cloned github
repo, stored in:
/Users/me/my_teams_code/some_project/package/IWantThisClass.py
But let's say I have some other projects here:
/Users/me/my_own_code/some_other_project1/...
/Users/me/my_own_code/some_other_project2/...
/Users/me/my_own_code/some_other_project3/...
each of which use IWantThisClass. One strategy seems to be to just manually
add the correct directory to sys.path every time, but this is rather
cumbersome - especially when I'm just experimenting in a Jupyter notebook. The
solution that I settled upon after googling around is to add the package
directory to my PYTHONPATH variable in bash; this works in the sense that
"import IWantThisClass" works just fine. But I read in Coghlan's post above:
> "This next trap exists in all current versions of Python, including 3.3, and
> can be summed up in the following general guideline: 'Never add a package
> directory, or any directory inside a package, directly to the Python path'."
So what is the "correct" way to solve this problem?
Answer: Basically, if `package` is the top-level directory of your package, you should
add the directory _containing_ `package` to `sys.path`. If what you want to
import is not a package but a single module (i.e., just an individual `.py`
file not in a package directory), then that module should be in a directory on
`sys.path`/
Exactly how you should add these paths is another question. For situations
where I want to add one-off things to the path, I find that the easiest thing
to do is to create a `.PTH` file inside a "site directory" --- either the main
site-packages directory or the user-specific site-packages directory. In that
`.PTH` file you can list other directories which will then be added to
`site.path`. So you can have your own little `my_stuff.pth` file that sets up
`sys.path` with directories you need. This avoids having to add boilerplate
code to each script to manually modify `sys.path`. You can read about how to
do this in the documentation for the [`site`
module](https://docs.python.org/2/library/site.html).
Another, perhaps better answer is that you should try to avoid adding specific
directories to `sys.path` in order to access specific files. Rather, you
should try to _install_ the relevant packages, which will let Python set up
the paths for you. If you're using in-development packages that you don't want
to clutter your main site-packages will, you can use [`python setup.py
develop`](https://pythonhosted.org/setuptools/setuptools.html#development-
mode) or [`pip install
--editable`](https://pip.pypa.io/en/latest/reference/pip_install.html#editable-
installs) to install the packages "in-place". (That is, the package files will
stay where they are, not be moved into the global Python site-packages, and
the installer will update the appropriate `.PTH` files so that the newly-
installed package is importable.)
In short, ultimately you need to move away from viewing it in terms of "this
file wants this class from this other file". The unit that you should be
concerned with is the installable package or module. If you're writing code
that wants SomeClass, you should install the package/module that provides
SomeClass and then import it; don't try to manipulate `sys.path` on an ad-hoc
basis to target the individual file/class that you want without installing its
package. (As mentioned, `setup.py develop` and `pip install --editable` allow
you to do this while still keeping the actual files where you want.)
|
Why does setuptools not understand git+https URLs?
Question: According to [Dependency section in the setuptools
manual](https://pythonhosted.org/setuptools/setuptools.html#dependencies-that-
aren-t-in-pypi) `git` repository URLs can be specified in the
`dependency_links` argument to `setup` with `git+URL`. Yet,
cd /tmp
mkdir py-test
cd py-test
touch __init__.py
and creation of a `setup.py` file with
from setuptools import setup, find_packages
from pkg_resources import parse_version
setup(
name = "py-test",
version = "1.0",
packages = ["."],
dependency_links = [
"git+https://github.com/wxWidgets/wxPython.git"
],
install_requires = ["wxPython"],
)
causes the error `Download error on
git+https://github.com/wxWidgets/wxPython.git: unknown url type: git+https --
Some packages may not be found!` when I run `python setup.py build && sudo
setup.py install`.
The installation of the package `python-setuptools-git` doesn't help.
I'm using `setuptools` 18.2 with `python` 2.7 on Ubuntu 15.04.
Answer: From the [setuptools
docs](https://pythonhosted.org/setuptools/setuptools.html):
> In the case of a VCS checkout, you should also append #egg=project-version
> in order to identify for what package that checkout should be used
So the fix is just to append the `#egg=wxPython` fragment onto the end:
dependency_links = [
"git+https://github.com/wxWidgets/wxPython.git#egg=wxPython"
]
|
Trouble Graphing Data with Python
Question: I'm trying to create a program that will allow me to create a line graph of
random 10 year intervals of stocks. I'm able to get the data into a DataFrame
using pandas, but when I try to plot the information it won't pull up any
graph. There's no error so I'm stuck as to what could be going wrong. Any help
would be appreciated.
import requests
import numpy as np
from urllib2 import urlopen
import csv
import pandas as pd
from pandas import *
from pandas import DataFrame as df
import datetime
import pandas.io.data
from random import randint
import matplotlib.pyplot as plt
YahooUrl = 'http://ichart.yahoo.com/table.csv?s='
start_month = 1 - 1
start_day = 1
start_year = 2010
end_month = 12 - 1
end_day = 31
end_year = 2014
Start_ApiMonth = '&a=%s' %(start_month)
Start_ApiDay = '&b=%s' %(start_day)
Start_ApiYear = '&c=%s' %(start_year)
End_ApiMonth = '&d=%s' %(end_month)
End_ApiDay = '&e=%s' %(end_day)
End_ApiYear = '&f=%s' %(end_year)
interval = 'm'
ApiInterval = '&g=%s' %(interval)
ApiStatic = '&ignore=.csv'
Ticker = 'aapl'
Website = urlopen(YahooUrl + Ticker + Start_ApiMonth + Start_ApiDay + Start_ApiYear + End_ApiMonth + End_ApiDay + End_ApiYear + ApiInterval + ApiStatic)
Info = pd.read_csv(Website)
Table = df(Info)
def Interval():
end = randint(9,len(Table))
start = end-10
group = [start]
while start <= end:
group.append(start+1)
start = start + 1
return group
interval = Interval()
TableGraph = []
TableGraph = Table['Adj Close'][interval]
points = []
for i in interval:
points.append(Table['Adj Close'][i])
TG = DataFrame(points, index=list('abcdefghijkl'), columns=list('x'))
TG.plot()
print Table
Answer: You need to call show after plot:
plt.show()
Which will give you something like:
[](http://i.stack.imgur.com/p03QU.png)
|
Python 2.7 Output from text files without last blank line
Question: I've started to learn Python and I stucked on one task - I have 10 text files
and I am trying to write from them two outputs: Output 1 should look like
folder and name of file header folder and name of file header ...
Output 2 should look like folder and name of file | text | text | text folder and name of file | text | text | text ...
Although I looked throught many of questions, I have not found, how to delete
(or not write) last blank row - there should be always only text. All
solutions I tried (tell(), rstrip(), ...) deleted all signs for new line, so I
had file like folder and name of file headerfolder and name of file header.
Ufortunatelly because of the task definition I am allowed to use only glob and
re, so helpful sys is forbidden for me :(
I would really appreciate your help with that, this task is for me really
challenging but now I do not know how to continue :)
Thanks for any advice and have a nice day ;)
Code I am using:
import re, glob
file_list = glob.glob('./input/*txt')
for file_name in file_list:
input_file = open(file_name, 'r')
output_1 = open('file_1', 'a')
output_2 = open('file_2', 'a')
for line in input_file:
if re.search(r'\s{2,}\S{4,}\s{1}\S+:.*', line):
output_2.write(file_name.replace('.txt','|') + line)
if re.search(r'\s{3,}\S{3,16}\s+X?\s[A-Z]{3,4}\d?\s+\d{1,3}.*', line):
field = re.findall('\S{3,16}\s{3,}', line) + re.findall('\s{2}\d{1,3}.*', line)
field_join = '|'.join(field)
field_clear = re.sub(r'(\s){2,}', '', field_join)
field_list = re.sub(' ', '|', field_clear, 1)
output_1.write(file_name.replace('.txt','|') + field_list + '\n')
output_2.close()
output_1.close()
input_file.close()
Answer: At the beginning of the loop just `continue` (immediately go to next loop
iteration without executing any more code) if it's a blank line:
for line in input_file:
if not line.strip():
continue
# etc
EDIT: For only the last line if it's blank:
input_file = input_file.readlines()
last_iter = len(input_file) - 1
for idx, line in enumerate(input_file):
if idx == last_iter and not line.strip():
break
Or before the loop:
input_file = input_file.readlines()
if not input_file[-1].strip():
input_file = input_file[:-1]
|
Python error: TypeError: '_csv.reader' object is not subscriptable
Question: I am working on creating a change calculator that has to output a result
similar to this:
{'TWENTY':1, 'TEN':1, 'FIVE':1, 'PENNY’ : 2}
{‘ONE’:1,'FIVE':1}
{‘ONE’:1}
{'PENNY':4,'NICKEL':1}
I am having issues with reading the data and accessing the indices because I
have never worked with reading a .csv file before. I think the logic of my
calculator should be fine. I realize there are more efficent ways to code it
but I am on a time limit and this seemed logical to me. Any help is
appreciated.
Thanks
enter code here__author__ = 'austincolaizzi'
import csv
print("Enter in your file name: ")
file1 = input(" ")
txt1 = open(file1)
csv_txt1 = csv.reader(txt1)
#for row in csv_txt1:
#print (row[0:2])
difference = 0
remainder = 0
change = {
'Penny': 0,
'Nickel': 0,
'Dime': 0,
'Quarter': 0,
'Half Dollar': 0,
'One': 0,
'Two': 0,
'Five': 0,
'Ten': 0,
'Twenty': 0,
'Fifty': 0,
'Hundred': 0,
}
for row in csv_txt1:
if row[0] == row[1]:
print ("You had exact change")
elif row[0] > row[1]:
print ("You need more money to purchase this")
else:
difference = csv_txt1[1] - csv_txt1[0]
if difference % 100 == 0:
remainder = remainder
elif difference % 100 != 0:
change['Hundred'] = difference / 100
remainder = difference % 100
elif remainder % 50 == 0:
remainder = remainder
elif remainder % 50 != 0:
change['Fifty'] = remainder / 50
remainder = remainder % 50
elif remainder % 20 == 0:
remainder = remainder
elif remainder % 20 != 0:
change['Twenty'] = remainder / 20
remainder = remainder % 20
elif remainder % 10 == 0:
remainder = remainder
elif remainder % 10 != 0:
change['Ten'] = remainder / 10
remainder = remainder % 10
elif remainder % 5 == 0:
remainder = remainder
elif remainder % 5 != 0:
change['Five'] = remainder / 5
remainder = remainder % 5
elif remainder % 2 == 0:
remainder = remainder
elif remainder %2 != 0:
change['Two'] = remainder / 2
remainder = remainder % 2
elif remainder % 1 == 0:
remainder = remainder
elif remainder %1 != 0:
change['Two'] = remainder / 1
remainder = remainder % 1
elif remainder % int(.50) == 0:
remainder = remainder
elif remainder % int(.50) != 0:
change['Two'] = remainder / int(.50)
remainder = remainder % int(.50)
elif remainder % int(.25) == 0:
remainder = remainder
elif remainder % int(.25) != 0:
change['Two'] = remainder / int(.25)
remainder = remainder % int(.25)
elif remainder % int(.10) == 0:
remainder = remainder
elif remainder % int(.10) != 0:
change['Two'] = remainder / int(.10)
remainder = remainder % int(.10)
elif remainder % int(.05) == 0:
remainder = remainder
elif remainder % int(.05) != 0:
change['Two'] = remainder / int(.05)
remainder = remainder % int(.05)
else:
remainder = remainder / int(.01)
for key in change:
if change[key] >= 1:
print (change[key])
Answer: In the line after your else statement, you have `csv_txt1[1] - csv_txt1[0]`.
This should be `row[1] - row[0]`, as you have earlier.
Note you should have posted the traceback, which would have made this easier
to debug as it shows the exact line the error occurred on.
|
Python decode nested JSON in JSON
Question: I'm dealing with an API that unfortunately is returning malformed (or "weirdly
formed," rather -- thanks @fjarri) JSON, but on the positive side I think it
may be an opportunity for me to learn something about recursion as well as
JSON. It's for an app I use to log my workouts, I'm trying to make a backup
script.
I can received the JSON fine, but even after `requests.get(api_url).json()`
(or `json.loads(requests.get(api_url).text)`), one of the values is still a
JSON encoded string. Luckily, I can just `json.loads()` the string and it
properly decodes to a dict. The specific key is predictable: `timezone_id`,
whereas its value varies (because data has been logged in multiple timezones).
For example, _after_ decoding, it might be: `dump`ed to file as
`"timezone_id": {\"name\":\"America/Denver\",\"seconds\":\"-21600\"}"`, or
`load`ed into Python as `'timezone_id':
'{"name":"America/Denver","seconds":"-21600"}'`
The problem is that I'm using this API to retrieve a fair amount of data,
which has several layers of dicts and lists, and the double encoded
`timezone_id`s occur at multiple levels.
Here's my work so far with some example data, but it seems like I'm pretty far
off base.
#! /usr/bin/env python3
import json
from pprint import pprint
my_input = r"""{
"hasMore": false,
"checkins": [
{
"timestamp": 1353193745000,
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"privacy_groups": [
"private"
],
"meta": {
"client_version": "3.0",
"uuid": "fake_UUID"
},
"client_id": "fake_client_id",
"workout_name": "Workout (Nov 17, 2012)",
"fitness_workout_json": {
"exercise_logs": [
{
"timestamp": 1353195716000,
"type": "exercise_log",
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"workout_log_uuid": "fake_UUID"
},
{
"timestamp": 1353195340000,
"type": "exercise_log",
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"workout_log_uuid": "fake_UUID"
}
]
},
"workout_uuid": ""
},
{
"timestamp": 1354485615000,
"user_id": "fake_ID",
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"privacy_groups": [
"private"
],
"meta": {
"uuid": "fake_UUID"
},
"created": 1372023457376,
"workout_name": "Workout (Dec 02, 2012)",
"fitness_workout_json": {
"exercise_logs": [
{
"timestamp": 1354485615000,
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"workout_log_uuid": "fake_UUID"
},
{
"timestamp": 1354485584000,
"timezone_id": "{\"name\":\"America/Denver\",\"seconds\":\"-21600\"}",
"workout_log_uuid": "fake_UUID"
}
]
},
"workout_uuid": ""
}]}"""
def recurse(obj):
if isinstance(obj, list):
for item in obj:
return recurse(item)
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, str):
try:
v = json.loads(v)
except ValueError:
pass
obj.update({k: v})
elif isinstance(v, (dict, list)):
return recurse(v)
pprint(json.loads(my_input, object_hook=recurse))
Any suggestions for a good way to `json.loads()` all those double-encoded
values without changing the rest of the object? Many thanks in advance!
This post seems to be a good reference: [Modifying Deeply-Nested
Structures](http://nvie.com/posts/modifying-deeply-nested-structures/)
Edit: This was flagged as a possible duplicate [of this
question](http://stackoverflow.com/questions/2331943/how-to-decode-json-with-
python) \-- I think its fairly different, as I've already demonstrated that
using `json.loads()` was not working. The solution ended up requiring an
`object_hook`, which I've never had to use when decoding json and is not
addressed in the prior question.
Answer: So, the `object_hook` in the json loader is going to be called each time the
json loader is finished constructing a dictionary. That is, the first thing it
is called on is the _inner-most_ dictionary, working outwards.
The dictionary that the `object_hook` callback is given is _replaced_ by what
that function returns.
So, you don't need to recurse yourself. The loader is giving you access to the
inner-most things first by its nature.
I think this will work for you:
def hook(obj):
value = obj.get("timezone_id")
# this is python 3 specific; I would check isinstance against
# basestring in python 2
if value and isinstance(value, str):
obj["timezone_id"] = json.loads(value, object_hook=hook)
return obj
data = json.loads(my_input, object_hook=hook)
It seems to have the effect I think you're looking for when I test it.
I probably wouldn't try to decode every string value -- I would strategically
just call it where you expect there to be a json object double encoding to
exist. If you try to decode every string, you might accidentally decode
something that is supposed to be a string (like the string `"12345"` when that
is intended to be a string returned by the API).
Also, your existing function is more complicated than it needs to be, might
work as-is if you always returned `obj` (whether you update its contents or
not).
|
Unable to install modules for anaconda
Question:
abhigenie92@ubuntu:~/Desktop/pygame-1.9.1release$ which python
/home/abhigenie92/anaconda/bin/python
abhigenie92@ubuntu:~/Desktop/pygame-1.9.1release$ sudo apt-get install python-pygame
Reading package lists... Done
Building dependency tree
Reading state information... Done
python-pygame is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 224 not upgraded.
abhigenie92@ubuntu:~/Desktop/pygame-1.9.1release$ python
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 17:02:03)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> import pygame
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named pygame
What is happening above? It seems to not install for anaconda. But it is
directing to the right from path.
Answer: You are installing things into the system Python. You need to install into the
Anaconda Python, using `pip install pygame` (note that `sudo pip` is likely
going to use the system Python again, and using `sudo` with the Anaconda
Python is not recommended anyway).
|
ValueError("No JSON object could be decoded") Python googlemaps
Question: I am using Google app engine (v1.9.24) with flask (v0.10.1) and python
(v2.7.5).
I'm trying to get the googlemaps (v2.2) API to work with my app.
I know the JSON returned is badly formatted but I don't why.
My code is below:
import googlemaps
gmaps = googlemaps.Client(key='API_KEY')
geocode_result = gmaps.geocode('6b, oko awo, victoria island, lagos')
return geocode_result
This works perfectly, but returns a badly formatted JSON string (I confirmed
this by running the same code on my local machine).
I used [JSON validator](http://jsonlint.com) to validate the JSON it returned.
And because of the badly fomatted JSON my flask app crashes and gives me a
ValueError. I don't know a way around this and I'd appreciate any help.
Answer: The problem is not with the JSON. Actually,
gmaps.geocode('6b, oko awo, victoria island, lagos')
doesn't return JSON at all, it returns a list that holds the value of "result"
as documented in [the google
docs](https://developers.google.com/maps/documentation/geocoding/intro), as
you can see [here](https://github.com/googlemaps/google-maps-services-
python/blob/master/googlemaps/geocoding.py) in the source code for googlemaps
library.
What is actually returned is a list object filled with data. All the string
values inside this list are unicode strings. That means they look like
`u'hello'` instead of plain `"hello"` (note the double quotes) that
json.loads() expects (I assume that is how you are trying to load the JSON).
This probably means that the problem you're trying to solve a non existing
problem. You don't have to load the JSON, because it already is a python list
object.
You can confirm by doing
json.loads(json.dumps(geocode_result))
it works fine, meaning there is no problem with the JSON structure.
|
How to make Python's multiprocessing Queue's .empty() method return the correct value? Or alternatives?
Question: I have this snippet that uses the `Queue` class from the `multiprocess`
module. I am very confused that the `.empty()` method of an instance of
`Queue` does not give me a correct value as i would expect. This is my code:
from time import sleep
from multiprocessing import Queue, Lock
foo = Queue()
locker = Lock()
with locker: # even with this, still True
foo.put("bar")
print(foo.empty()) # True, obviously not
print(foo.empty()) # True
print(foo.empty()) # True
print(foo.qsize()) # 1L
print(foo.empty()) # True
However, if i use the `sleep` function from `time`, as in cause a
chronological delay in the execution. It works.
from time import sleep
from multiprocessing import Queue, Lock
foo = Queue()
locker = Lock()
foo.put("bar")
sleep(0.01)
print(foo.empty()) # False
print(foo.empty()) # False
print(foo.empty()) # False
print(foo.qsize()) # 1L
print(foo.empty()) # False
I know my alternative is the `.qsize() > 0` expression, but i am sure that i
just doing this in a wrong way.
What am i doing wrong?
***EDIT***
I understand now that is it _unreliable_ , thank you @Mathias Ettinger. Any
clean alternatives? I need to know hot to reliably tell if my `Queue` is empty
or not.
Answer: Unfortunately, the Queue's complex implementation that means that `.empty()`
isn't guaranteed to be correct immediately, even though `.qsize()` is.
Since `.qsize()` _is_ supported on your platform (which is [not true
everywhere](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue.qsize)),
you can re-implement the `.empty()` check in terms of `.qsize()`, and this
will work for you:
# mp.Queue() is a function, not a class, so we need to find the true class
# to subclass
import multiprocessing.queues
class XQueue(multiprocessing.queues.Queue):
def empty(self):
try:
return self.qsize() == 0
except NotImplementedError: # OS X -- see qsize() implementation
return super(XQueue, self).empty()
Under the hood, the Queue `.put()`s your objects to a buffer and increments an
interprocess semaphore, while a hidden daemon thread is responsible for
draining the buffer and serializing its contents to a pipe. (Consumers then
`.get()` by reading from this pipe.) So, that's why sleeping in your example
works: the daemon thread has enough time to move the object from in-memory
buffer to I/O representation before you call `.empty()`.
As an aside, I find this behavior _very_ surprising. Normally when we say a
queue's size methods (empty/full/count) are "unreliable," we mean they're
_accurate and consistent_ , but _possibly immediately stale_ because another
producer or consumer might have changed the queue. (Most single-process
multithreaded queues, like python's `Queue.Queue`, for example, are
"unreliable" but consistent in this sense.) In this case, the default
`.empty()` method really can be inconsistent with the state of the queue.
|
When is a variable released from memory?
Question: Say I define a function, which builds a list, and then prints the items of the
list one by one (no practical use, just an example:
import os
def build_and_print():
thingy = os.walk('some directory')
for i in thingy:
print i
if __name__ == '__main__:
build_and_print()
If the `thingy` that is built is very large it could take up a lot of memory,
at what point will it be released from memory?
Does python store the variable `thingy` until the script is finished running
or until the function that builds/uses it is finished running?
Answer: Once a Variable goes **out of scope** , it is collected by the garbage
collector.
You can see the collector [code
here.](https://hg.python.org/cpython/file/tip/Modules/gcmodule.c) Go to
collect function, there comments explain the process well.
|
Converting text file to list and getting at it using indexes:
Question: Can anyone tell me why this doesn't work (Python 3) and what I need to do to
fix it. Code and error message below:
def verifylogin():
fin=open("moosebook.txt","r")
data=fin.readlines()
line=data
allData = []
for ln in line.split(')('):
allData.append( ln.lstrip('(').rstrip(')').replace("'", '').replace(' ', '').split(',') )
for data in allData:
print (data[0]) # print user
print (data[5]) # print profession
output error message:
line 30, in verifylogin
for ln in line.split(')('):
AttributeError: 'list' object has no attribute 'split'
The data in the text file is:
('CoderBlogJ', 'ggs123', 'J', 'Bloggs', 'Male', 'Coder')('DoctorSmitD', 'ith123', 'D', 'Smith', 'Male', 'Doctor')('teacherminaR', 'neb123', 'R', 'minajneb', 'female', 'teacher')('WriterGardK', 'ens123', 'K', 'Gardens', 'Male', 'Writer')('', '123', '', '', '', '')('', '123', '', '', '', '')('', '123', '', '', '', '')
I want data[0] and data[5] etc to print out the relevant field in the list.
Thank you very much for the answer: My final quest however, is to get the
username and password to work and because I can't translate it, I can't quite
get it to work ....
def verifylogin():
with open("moosebook.txt") as f:
data = literal_eval(f.read().replace(")", "),"))
for user, pw,_,sur,_, job in data:
if user:
print("{} is a {}".format(user, pw))
flag=0
for counter in range(0,len(data)):
if textlogin.get()==data[counter] and textpassword.get()==data[counter+1]:
flag=flag+1
if flag>0:
welcome=Label(myGui,text="Access Granted. Loading Profile ....")
welcome.pack()
else:
denied=Label(myGui,text="Access Denied")
denied.pack()
Answer: Your error as stated already is because line is a reference to data which is a
list, if each tuple is on a separate line in your file you can use
ast.literal_eval to parse the data and just index the tuples to get the dat
you want:
from ast import literal_eval
def verifylogin():
with open("test.csv") as f:
for line in f:
print(literal_eval(line))
verifylogin()
Output:
('CoderBlogJ', 'ggs123', 'J', 'Bloggs', 'Male', 'Coder')
('DoctorSmitD', 'ith123', 'D', 'Smith', 'Male', 'Doctor')
('teacherminaR', 'neb123', 'R', 'minajneb', 'female', 'teacher')
('WriterGardK', 'ens123', 'K', 'Gardens', 'Male', 'Writer')
('', '123', '', '', '', '')
('', '123', '', '', '', '')
('', '123', '', '', '', '')
If you have it all in a single line you can `str.replace` putting a trailing
comma after each `)`, that will wrap all the tuples in a tuple so ast can
parse the file content correctly:
def verifylogin():
with open("test.csv") as f:
data = literal_eval(f.read().replace(")", "),"))
for t in data:
print(t)
verifylogin()
Output will be the same as previously.
If you are using python3 we can use [extended iterable
unpacking](https://www.python.org/dev/peps/pep-3132/) to get the data we want,
ignoring the data with no user with an if check:
from ast import literal_eval
def verifylogin():
with open("test.csv") as f:
data = literal_eval(f.read().replace(")", "),"))
for user, *rest, job in data: # python2 -> for user, _,_,_,_, job in data:
if user:
print("{} is a {}".format(user, job))
Output:
CoderBlogJ is a Coder
DoctorSmitD is a Doctor
teacherminaR is a teacher
WriterGardK is a Writer
You can get whatever info you want, all the data is unpacked in the loop:
def verifylogin():
with open("test.csv") as f:
data = literal_eval(f.read().replace(")", "),"))
for user, pw, _, _ , _, job in data:
if user:
print("Details for user: {}\nPassword: {}\nJob: {}\n".format(user, pw, job))
Output:
Details for user: DoctorSmitD
Password: ith123
Job: Doctor
Details for user: teacherminaR
Password: neb123
Job: teacher
Details for user: WriterGardK
Password: ens123
Job: Writer
|
Python wand drawed polygons instead of rectangle when stroke_width > 2
Question: I'm not sure what I did wrong, but this is really strange. Not sure whether I
should submit a new issue to wand's Git repository.
edit: I am trying to draw a rectangle.
Consider the following code:
from wand.drawing import Drawing
from wand.color import Color
from wand.image import Image
def drawer():
square = Drawing()
square.fill_color = Color('#fff')
square.stroke_width = 4
square.stroke_color = Color('red')
square.rectangle(left=100, top=100, width=100, height=100)
return square
im = Image(width=500, height=500)
sq = drawer()
sq.draw(im)
im.save(filename='test1.png')
And this outputs:
[](http://i.stack.imgur.com/4fiHj.png)
From what I've tried-and-error'd, this won't happen if `square.stroke_width`
is less or equal than 2.
I'm not sure whether it's Wand's bug or I am doing something wrong.
Answer: It should work fine according to <http://docs.wand-
py.org/en/0.4.1/guide/draw.html> . If you go to the bottom of the page it
shows how to draw polygons. Compared to what your code looks like, it should
work fine. I don't know what's wrong, but I'm pretty sure your code is OK.
|
How to calculate frequency of each number and display results as a table
Question: I have the following numbers:
x = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9]
Now I want to calculate frequency of each number and display results as a
table using, e.g. [tabulate](https://pypi.python.org/pypi/tabulate).
I calculate frequencies this way:
import collections
c = collections.Counter(x)
count_sum = sum(c.values())
for key,value in c.iteritems():
print str(key) + " - " + str(float(value) / count_sum)
I don't know how to create an array of and pass it to `tabulate`. The ideal
solution would be to use `numpy`.
Answer: Based on comments of Jose Ricardo Bustos M. and JonasL:
The answer for Python 2.8 is:
print(tabulate([[key,float(val)/count_sum] for key,val in c.iteritems()]))
To get numbers from x, it is necessary to use `key`, while `val` defines
absolute frequency (count) of a number.
|
Major Difference in 2D kernel Density Plots: Seaborn and R
Question: I am trying to plot data using the 2D kernel density plot of Seaborn's
jointplot function (using statsmodels' KDEMultivariate function to calculate a
data-driven bandwidth). I've plotted a 2D kernel density in R using the same
data and the result looks very good (using the 'ks' package), while the
Seaborn plot looks very very different.
I am using the same exact data and the same exact bandwidth for each (taking
the bandwidth given by KDEMultivariant and passing that to the R method).
Here is the input.csv data used:
<https://app.box.com/s/ot7d36t44wrr85pusp5657pc1w2kf5hj>
Below are the code used in each and output images from each.
Python / Seaborn:
import matplotlib.pyplot as plt
import statsmodels.api as sm
data = pd.read_csv("input.csv", dtype={'x': float, 'y': float}, skiprows=0)
bw_ml_x = sm.nonparametric.KDEMultivariate(data=data['x'], var_type='c', bw='cv_ml')
bw_ml_y = sm.nonparametric.KDEMultivariate(data=data['y'], var_type='c', bw='cv_ml')
g = sns.jointplot(x='x', y='y', data=data, kind="kde", stat_func=None, bw=[bw_ml_x.bw, bw_ml_y.bw])
g.plot_joint(plt.scatter, c="w")
g.ax_joint.collections[0].set_alpha(0)
sns.plt.show()
Img for Seaborn plot:

The bandwidth given by bw_ml_x.bw and bw_ml_y.bw is placed in a 2 x 2 R matrix
H, where H[1,1] = bw_ml_x.bw, H[2,2] = bw_ml.y.bw, and other values set to
zero.
R:
library(ks)
fhat <- kde(x=as.data.frame(data[1], data[2]), H=H)
plot(fhat, display="filled.contour2", cont=seq(10,90,by=10))
Img for R plot:

Answer: Looking at your Seaborn/Python plot, many of the points cluster along the
(0,n) region and the (1,1) region of your space, just as the KDE of the R plot
shows. This indicates that Seaborn and R are looking at the same data; we
simply need to reformulate the call to the `kde` in Seaborn in order to
visualize the KDE gradients.
If you modify your Python call to match the
[documentation](https://stanford.edu/~mwaskom/software/seaborn/tutorial/distributions.html)
for `Kernel Density Estimation` in Seaborn you'll get a proper 2d-kdf out of
Python:
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd
import seaborn as sns
data = pd.read_csv("input.csv", dtype={'x': float, 'y': float}, skiprows=0)
bw_ml_x = sm.nonparametric.KDEMultivariate(data=data['x'], var_type='c', bw='cv_ml')
bw_ml_y = sm.nonparametric.KDEMultivariate(data=data['y'], var_type='c', bw='cv_ml')
g = sns.jointplot(x='x', y='y', data=data, kind="kde")
g.plot_joint(plt.scatter, c="w")
g.ax_joint.collections[0].set_alpha(0)
sns.plt.show()
[](http://i.stack.imgur.com/AuNkZ.png)
This accords with the R plot (though the kernel estimators seem to be slightly
different, which would account for the variation in gradients between the
plots):
[](http://i.stack.imgur.com/8nYhn.png)
|
Gspread & Oauth2 on Python 3.4 - Oauth does not support indexing
Question: I want to use gspread and since client authentication is outdated, I'm trying
with Oauth2. I'm new to both gspread & Oauth2.
Piecing together [from this basic Oauth2
example](https://developers.google.com/api-client-
library/python/guide/aaa_oauth) and [the gspread
documentation](https://github.com/burnash/gspread) I have the most basic login
function.
import gspread
from oauth2client.client import OAuth2WebServerFlow
CLIENT_ID = 'my id'
CLIENT_SECRET = 'my secret key'
flow = OAuth2WebServerFlow(client_id= CLIENT_ID,
client_secret= CLIENT_SECRET,
scope='https://docs.google.com/spreadsheets/',
redirect_uri='http://localhost:80')
gc = gspread.authorize(flow)
The problem is that I get this error.
> TypeError: 'OAuth2WebServerFlow' object does not support indexing
from the larger
> C:\Python34\lib\site-packages\gspread\client.py:73: Warning: ClientLogin is
> deprecated:
> <https://developers.google.com/identity/protocols/AuthForInstalledApps?csw=1>
>
>
> Authorization with email and password will stop working on April
> 20, 2015.
>
> Please use oAuth2 authorization instead:
> http://gspread.readthedocs.org/en/latest/oauth2.html
>
>
> """, Warning) Traceback (most recent call last): File
> "C:\Users\family\Desktop\mygspread.py", line 13, in gc =
> gspread.authorize(flow) File "C:\Python34\lib\site-
> packages\gspread\client.py", line 335, in authorize client.login() File
> "C:\Python34\lib\site-packages\gspread\client.py", line 105, in login data =
> {'Email': self.auth[0], TypeError: 'OAuth2WebServerFlow' object does not
> support indexing
Since both are official scripts - one from google and the other from burnash,
I'm not sure what to change. I know the question is basic, but how do I log in
with Python 3.4?
Answer: I've figured it out. If anyone else is interested, this is what I needed to do
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
json_key = json.load(open('Gspread-762ec21ac2c5.json'))
scope = ['https://spreadsheets.google.com/feeds']
credentials = SignedJwtAssertionCredentials(json_key['client_email']
, bytes(json_key['private_key']
, 'utf-8')
, scope)
gc = gspread.authorize(credentials)
wks = gc.open("mytestfile").sheet1
|
winshell.shortcut(parent) giving 'module has no attribute 'shortcut'
Question: -Update at the bottom-
pywin32 & winshell installed with no apparent errors, but the following test
code (extracted from the example here: [winshell
examples](https://winshell.readthedocs.org/en/latest/cookbook/shortcuts.html#read-
details-from-an-existing-shortcut) ):
import winshell
parent = 'H:\MUSIC\TESTC\TESTTB.lnk' # target is H:\MUSIC\TESTB
with winshell.shortcut(parent) as link:
print(link.path)
produced this result:
> Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:\Python33\MyScripts\Audio\shortcut2.py", line 3, in <module>
with winshell.shortcut(parent) as link:
AttributeError: 'module' object has no attribute 'shortcut'
>>>
Presumably something must, in fact, not be right with the winshell install -
what should I be looking for?
PS: The system seems to require the output on the python window to be
formatted as code which it clearly is not. Curious as to why. It does
_contain_ a code fragment but that's not the same thing.
* update - Most of the other methods shown in the docs are not in the dir(winshell) output (eg the file methods such as copy_file):
>>> dir(winshell)
>>> ['__RELEASE__', '__VERSION__', '__builtins__',
>>> '__cached__', '__doc__', '__file__',
>>> '__initializing__', '__loader__', '__name__',
>>> '__package__', '__path__']
Answer: Problem solved after some assistance from [@Maksim
Yegorov](http://stackoverflow.com/users/5293595/maksim-yegorov). The problem
was that the installation process automatically put the winshell files into
.../Lib/site-packages/winshell.
However for the example code to work they need to be in .../Lib/site-packages
If they are to be in their own folder then instead of
`from winshell import shortcut` its `from winshell.winshell import shortcut`
and line 26 of winshell.py needs to be modified in like manner to `from
winshell.__winshell_version__ import __VERSION__`
The winshell docs may need to be clarified to avoid this.
|
error while writing to a Mysql wih python NetCDF
Question:
#!/usr/bin/env python3
import datetime as dt # Python standard library datetime module
import numpy as np
from netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/
import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid
import mysql.connector as sql
from mysql.connector import errorcode
import sys
import getpass
import hashlib
import os
import netCDF4
import sys, traceback
def dbInsertGlobalAttributeCreateTable(cursor):
##Table name parameter is required later
TABLES = {}
TABLES['cmip5gloAtt'] = (
"CREATE TABLE `cmip5gloAtt` ("
" `id` int(100) AUTO_INCREMENT NOT NULL,"
" `institution` varchar(100) NOT NULL,"
" `source` varchar(100) NOT NULL,"
" `forcing` varchar(100) NOT NULL,"
" `parent_experiment_id` varchar(100) NOT NULL,"
" `branch_time` varchar(100) NOT NULL,"
" `contact` varchar(100) NOT NULL,"
" `initialization_method` varchar(100) NOT NULL,"
" `physics_version` varchar(100) NOT NULL,"
" `tracking_id` varchar(100) NOT NULL,"
" `experiment` varchar(100) NOT NULL,"
" `creation_date` varchar(100) NOT NULL,"
" `Conventions` varchar(100) NOT NULL,"
" `table_id` varchar(100) NOT NULL,"
" `parent_experiment` varchar(100) NOT NULL,"
" `realization` varchar(100) NOT NULL,"
" `cmor_version` varchar(100) NOT NULL,"
" `comments` varchar(100) NOT NULL,"
" `history` varchar(100) NOT NULL,"
" `references` varchar(100) NOT NULL,"
" `title` varchar(100) NOT NULL,"
" PRIMARY KEY (`id`)"
") ENGINE=InnoDB")
for tableName, query in TABLES.items():
try:
cursor.execute(query)
return True
except sql.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print ("Table is already there %s" %(tableName))
return True
else:
print("Error is here %s" %(err.msg))
return False
def insertAttributeValues(cursor, values):
tupleValues = tuple(values)
addRecord = ("INSERT INTO cmip5gloAtt"
"(institution, source, forcing, parent_experiment_id, branch_time, contact, initialization_method, physics_version, tracking_id, experiment, creation_date, Conventions, table_id, parent_experiment, realization, cmor_version, comments, history, references, title) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
print(tupleValues)
try:
cursor.execute(addRecord, tupleValues)
except sql.error as err:
print("Error inserting name %s" %(err.msg))
globalAttributes = ['institution','source', 'forcing', 'parent_experiment_id','branch_time', 'contact', 'initialization_method', 'physics_version', 'tracking_id', 'experiment', 'creation_date', 'Conventions', 'table_id', 'parent_experiment', 'realization', 'cmor_version', 'comments', 'history', 'references', 'title']
valueList = list()
datafilePath = input("File/directory to translate: ").strip()
dbHost = input("Database Host?:")
dbName = input("Database to store NDN name?:")
dbUserName = input("Database username?:")
dbPasswd = getpass.getpass("Database password?:")
print("full path is %s", datafilePath)
print("what is ", os.path.isfile(datafilePath))
if os.path.isfile(datafilePath) is True:
print ("os path worked")
fileName = os.path.split(datafilePath)[-1]
try:
with netCDF4.Dataset(datafilePath, 'r') as ncFile:
nc_attrs = ncFile.ncattrs()
print (nc_attrs)
for nc_attr in globalAttributes:
try:
print ('\t%s: ' % nc_attr, repr(ncFile.getncattr(nc_attr)))
valueList.append(repr(ncFile.getncattr(nc_attr)))
except:
print("NoAttribute: %s" %(nc_attr))
valueList.append("No particular value stored")
except:
print("Error")
try:
con = sql.connect(user=dbUserName, database=dbName, password=dbPasswd, host=dbHost)
cursor = con.cursor()
if dbInsertGlobalAttributeCreateTable(cursor):
boolResult = insertAttributeValues(cursor, valueList)
con.commit()
print("Return Code %s" %(boolResult))
else:
print("Creation table failed")
except sql.error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_CHANGE_USER_ERROR:
print("Incorrect username")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("DB is not there")
else:
print("Error connecting to DB %s" %(err.msg))
finally:
con.close()
It is a python code. I am sorry for improper indentation. I am trying to read
some information from a NetCDF file and wanted to write it to MySQL and i got
some errors that I cannot solve.
I believe that I put everything in correct syntax. I do not understand why
such error takes place..
Here is the detail.
Traceback (most recent call last):
File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 69, in insertAttributeValues
cursor.execute(addRecord, tupleValues)
File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 636, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 554, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'references, title) VALUES ('\'AORI (Atmosphere and Ocean Research Institute, The' at line 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 120, in <module>
boolResult = insertAttributeValues(cursor, valueList)
File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 70, in insertAttributeValues
except sql.error as err:
AttributeError: 'module' object has no attribute 'error'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 126, in <module>
except sql.error as err:
AttributeError: 'module' object has no attribute 'error'
Answer: `REFERENCES` is a [MySQL reserved
word](http://dev.mysql.com/doc/refman/5.6/en/keywords.html). If you wish to
use it as a column name you will need to surround it with backticks (`).
|
How to route an url to an specific method of a class Django and DRF
Question: I am very new in the python world and now I building an application with
Django 1.8 with the Rest Framework and I want to create a class view to DRY my
code.
For example I want to have a class view for the students in my system
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class SnippetList(APIView):
def getWorstStudents(self, request, format=None):
# Logic here
How can I assign a specified URL in **urls.py** to hit this method?
And also I have implemented **REST framework JWT Auth**
<http://getblimp.github.io/django-rest-framework-jwt/> for token auth.
How can I restrict the access to allow only authenticated users can access to
this url?
Thank you in advance!
Answer: You can set urls like any other Django app, [documented
here](https://docs.djangoproject.com/en/1.8/topics/http/urls/#example)
# urls.py
from django.conf.urls import url
from somewhere import SnippetList
urlpatterns = [
url(r'^your/url/$', SnippetList.as_view()),
]
About DRY with your method, you can define the method you want to response to,
and call the `getWorstStudents` (btw by convention I would call it
get_worst_students). Let's say you want to response the `post` method:
# views.py
from rest_framework.response import Response
def getWorstStudents(params)
class SnippetList(APIView):
def post(self, request, *args, **kwargs):
# call getWorstStudents method here and response a Response Object
You can define `getWorstStudents` inside `SnippetList` class or in other file
to import wherever you need it.
Finally, about authentication, DRF provides classes for this, [documented
here](http://www.django-rest-framework.org/api-guide/authentication/).
From docs, you need define this in your `settings.py` file:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
And use it in your views:
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
You can also define your own authentication class and set it in
`authentication_classes` tuple. [Custom authentication classes documented
here.](http://www.django-rest-framework.org/api-guide/authentication/#custom-
authentication)
|
How do I open a document (eg. .txt) in another app from a Python Script mac
Question: How and is it possible to open a document in a GUI text editor such as Word
from a python script on a Mac? For example, do something like this:
Open x.txt in Word.app
Answer: ## Here is how you can do it on Mac OS:
If you want to open a file with a specific application on Mac OS, you do:
$ open -a appName fileName
So, for example you want to open `hello.docx` with `Pages` app, you do:
$ open -a pages path/hello.docx
Similarly to open a file with Word:
$ open -a "Microsoft Word.app" path/hello.docx
## How you do it from Python (still only Mac OS):
Now, we need to be able to call shell commands from Python. There are several
ways of doing it. You can see [this
question](http://stackoverflow.com/questions/89228/calling-an-external-
command-in-python) for a variety of ways.
One simple way of doing it would be:
>>> import os
>>> os.system('open -a "Microsoft Word.app" path/hello.docx')
|
inserting a line in a file using python
Question: I have a file which contains data like this:
$ yum -- to install package
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
----->#i have to insert a new line here
$cat -- to read contents of a file
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
First, I have to find the the word `$ yum` in the file and insert a new line
before starting of the next word starting with `$`.
Some help with my code would be appreciated.
with open("test.txt", "a") as myfile:
for row in myfile:
if re.match(r'$yum,i):
myfile.append("user2,group,0123456,/usr/bin")
Answer: Opening the file with `a` does not allow you to `file_object.append(...`, it
means when you write to the file content will be added to the end of the file
so `myfile.append("user2,group,0123456,/usr/bin")` is not remotely valid
syntax.
You can use `itertools.groupby` to group by section where lines start with a
`$`, then either add a line if the line starts with `$ yum` or just write the
lines as is:
from itertools import groupby
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile("w",dir=".",delete=False) as out:
grps = groupby(f,key=lambda x: x.startswith("$"))
for k, v in grps:
if k:
val = next(v)
out.write(val)
if val.startswith("$ yum"):
out.writelines(next(grps,[[], [""]])[1])
out.write("I am a new line\n")
else:
out.writelines(v)
move(out.name,"in.txt")
The `move(out.name,"in.txt")` will change the original file content so the
output will be:
$ yum -- to install package
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
I am a new line
$cat -- to read contents of a file
admin1,group,n,0123456,/usr/bin
user2,group,n,0123456,/usr/bin
group,n,0123456,/usr/bin
Os use an inner loop every time you find a line starting with $ yum and
breaking and writing the new line in the inner loop whenever you find the next
`$`:
from tempfile import NamedTemporaryFile
from shutil import move
with open("in.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as out:
for line in f:
if line.startswith("$ yum"):
out.write(line)
for _line in f:
if _line.startswith("$"):
out.write("I am a new line\n")
out.write(_line)
break
out.write(_line)
else:
out.write(line)
move(out.name,"in.txt")
|
Why does unicode to string only work with try/except?
Question: Just when I thought I had my head wrapped around converting unicode to strings
Python 2.7 throws an exception.
The code below loops over a number of accented characters and converts them to
their non-accented equivalents. I've put in an special case for the double s.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import unicodedata
def unicodeToString(uni):
return unicodedata.normalize("NFD", uni).encode("ascii", "ignore")
accentList = [
#(grave accent)
u"à",
u"è",
u"ì",
u"ò",
u"ù",
u"À",
u"È",
u"Ì",
u"Ò",
u"Ù",
#(acute accent)
u"á",
u"é",
u"í",
u"ó",
u"ú",
u"ý",
u"Á",
u"É",
u"Í",
u"Ó",
u"Ú",
u"Ý",
#(arrete accent)
u"â",
u"ê",
u"î",
u"ô",
u"û",
u"Â",
u"Ê",
u"Î",
u"Ô",
u"Û",
#(tilde )
u"ã",
u"ñ",
u"õ",
u"Ã",
u"Ñ",
u"Õ",
#(diaresses)
u"ä",
u"ë",
u"ï",
u"ö",
u"ü",
u"ÿ",
u"Ä",
u"Ë",
u"Ï",
u"Ö",
u"Ü",
u"Ÿ",
#ring
u"å",
u"Å",
#ae ligature
u"æ",
u"Æ",
#oe ligature
u"œ",
u"Œ",
#c cidilla
u"ç",
u"Ç",
# D stroke?
u"ð",
u"Ð",
# o slash
u"ø",
u"Ø",
u"¿", # Spanish ?
u"¡", # Spanish !
u"ß" # Double s
]
for i in range(0, len(accentList)):
try:
u = accentList[i]
s = unicodeToString(u)
if u == u"ß":
s = "ss"
print("%s -> %s" % (u, s))
except:
pass
Without the try/except I get an error:
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xc0' in position 0
: character maps to <undefined>
Is there anything I can do to make the code run without using the try/except?
I'm using Sublime Text 2.
Answer: `try/except` does not make Unicode work. It just hides errors.
To fix the `UnicodeEncodeError` error, drop `try/except` and see [Python,
Unicode, and the Windows console](http://stackoverflow.com/a/32176732/4279).
|
python matplotlib: drawing 3D sphere with circumferences
Question: I'm trying to draw a sphere like this one using matplotlib:
[](http://i.stack.imgur.com/vXLle.png)
but I can't find a way of having a dashed lines on the back and the vertical
circumference looks a bit strange
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(12,12), dpi=300)
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 1 * np.outer(np.cos(u), np.sin(v))
y = 1 * np.outer(np.sin(u), np.sin(v))
z = 1 * np.outer(np.ones(np.size(u)), np.cos(v))
#for i in range(2):
# ax.plot_surface(x+random.randint(-5,5), y+random.randint(-5,5), z+random.randint(-5,5), rstride=4, cstride=4, color='b', linewidth=0, alpha=0.5)
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b', linewidth=0, alpha=0.5)
ax.plot(np.sin(theta),np.cos(u),0,color='k')
ax.plot([0]*100,np.sin(theta),np.cos(u),color='k')
[](http://i.stack.imgur.com/MI6E1.png)
Answer: In the example you show, I don't think that the circles can be perpendicular
to one another (i.e. one is the equator and one runs through the north pole
and south pole). If the horizontal circle is the equator, then the north pole
must be somewhere on a vertical line drawn through the center of the yellow
circle that represents the sphere. Otherwise, the right side of the equator
would look higher or lower than the left. However, the ellipse that represents
the polar circle only crosses through that center line at the top and bottom
of the yellow circle. Therefore, the north pole is at the top of the sphere,
which means that we must be looking straight on the equator, which means it
should look like a line, not an ellipse.
Here's some code to reproduce something similar to the figure you posted:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_aspect('equal')
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 1 * np.outer(np.cos(u), np.sin(v))
y = 1 * np.outer(np.sin(u), np.sin(v))
z = 1 * np.outer(np.ones(np.size(u)), np.cos(v))
#for i in range(2):
# ax.plot_surface(x+random.randint(-5,5), y+random.randint(-5,5), z+random.randint(-5,5), rstride=4, cstride=4, color='b', linewidth=0, alpha=0.5)
elev = 10.0
rot = 80.0 / 180 * np.pi
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b', linewidth=0, alpha=0.5)
#calculate vectors for "vertical" circle
a = np.array([-np.sin(elev / 180 * np.pi), 0, np.cos(elev / 180 * np.pi)])
b = np.array([0, 1, 0])
b = b * np.cos(rot) + np.cross(a, b) * np.sin(rot) + a * np.dot(a, b) * (1 - np.cos(rot))
ax.plot(np.sin(u),np.cos(u),0,color='k', linestyle = 'dashed')
horiz_front = np.linspace(0, np.pi, 100)
ax.plot(np.sin(horiz_front),np.cos(horiz_front),0,color='k')
vert_front = np.linspace(np.pi / 2, 3 * np.pi / 2, 100)
ax.plot(a[0] * np.sin(u) + b[0] * np.cos(u), b[1] * np.cos(u), a[2] * np.sin(u) + b[2] * np.cos(u),color='k', linestyle = 'dashed')
ax.plot(a[0] * np.sin(vert_front) + b[0] * np.cos(vert_front), b[1] * np.cos(vert_front), a[2] * np.sin(vert_front) + b[2] * np.cos(vert_front),color='k')
ax.view_init(elev = elev, azim = 0)
plt.show()
[](http://i.stack.imgur.com/BwVUA.png)
|
Finding specific URLs from a list of URLs using Python
Question: I want find if specific links exist in a list of URLs by crawling through
them. I have written the following program and it works perfectly. However, I
am stuck at 2 places.
1. Instead of using an array, how can I call the links from a text file.
2. The crawler takes close to 4 minutes to crawl through 100 webpages.
Is there a way I can make that faster.
from bs4 import BeautifulSoup, SoupStrainer
import urllib2
import re
import threading
start = time.time()
#Links I want to find
url = "example.com/one", "example.com/two", "example.com/three"]
#Links I want to find the above links in...
url_list =["example.com/1000", "example.com/1001", "example.com/1002",
"example.com/1003", "example.com/1004"]
print_lock = threading.Lock()
#with open("links.txt") as f:
# url_list1 = [url.strip() for url in f.readlines()]
def fetch_url(url):
for line1 in url_list:
print "Crawled" " " + line1
try:
html_page = urllib2.urlopen(line1)
soup = BeautifulSoup(html_page)
link = soup.findAll(href=True)
except urllib2.HTTPError:
pass
for link1 in link:
url1 = link1.get("href")
for url_input in url:
if url_input in url1:
with print_lock:
print 'Found' " " +url_input+ " " 'in'+ " " + line1
threads = [threading.Thread(target=fetch_url, args=(url,)) for url in url_list]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print('Entire job took:',time.time() - start)
Answer: If you want to read from a textfile, use the code you commented out.
As for the "performance" problem: Your code blocks at the read operation
`urlopen` until the content from the website is returned. You ideally want to
run those requests in parallel. You need a parallelized solution, by using
threads for example.
[Here's](https://github.com/gevent/gevent/blob/master/examples/concurrent_download.py)
an example using a different approach, using gevent (non-standard)
|
Python csv processing
Question: i have an python exercise that require write a program that extract
information from 5 csv file name QLD2010.csv, QLD2011.csv, QLD2012.csv,
QLD2013.csv and QLD2014.csv In each file there some data like that:
Girl Names,Count of Girl Names,Boy Names,Count of Boy Names
Ruby,440,Cooper,493
Mia,425,William,493
Isabella,401,Jack,452
And i have to merge data from 5 file to a new csv file with this format:
Year,Babyname,Count of names,Gender
eg.
2010,Harper,54,Girl
2010,Hunter,195,Boy
I have no idea how to make the 'year' from file name and how to merge girl
name and boy name in one row and show the gender. Anyone know how to do that?
Thanks!
Answer: If the filenames all have the same format, you can use slicing to get the
years easily;
In [1]: filenames = 'QLD2010.csv QLD2011.csv QLD2012.csv QLD2013.csv QLD2014.csv'.split()
In [2]: filenames
Out[2]: ['QLD2010.csv', 'QLD2011.csv', 'QLD2012.csv', 'QLD2013.csv', 'QLD2014.csv']
In [4]: [fn[3:7] for fn in filenames]
Out[4]: ['2010', '2011', '2012', '2013', '2014']
Or you might want to put them into a dictionary for easy access later;
In [5]: {fn: int(fn[3:7]) for fn in filenames}
Out[5]:
{'QLD2010.csv': 2010,
'QLD2011.csv': 2011,
'QLD2012.csv': 2012,
'QLD2013.csv': 2013,
'QLD2014.csv': 2014}
If the filenames are not so uniform, you could use regular expressions. The
expression `(\d{4})` basically means: match _exactly_ four digits, and return
the match as a group.
In [6]: import re
In [7]: {fn: int(re.search('(\d{4})', fn).group()) for fn in filenames}
Out[7]:
{'QLD2010.csv': 2010,
'QLD2011.csv': 2011,
'QLD2012.csv': 2012,
'QLD2013.csv': 2013,
'QLD2014.csv': 2014}
With regard to processing the lines from the CSV file, it is not that
difficult to split them up, assuming each line has the same form;
In [8]: 'Ruby,440,Cooper,493'.split(',')
Out[8]: ['Ruby', '440', 'Cooper', '493']
The easiest way to store the data is in a dictionary;
In [18]: boys, girls = {}, {}
In [19]: girls[row[0]] = int(row[1])
In [20]: boys[row[2]] = int(row[3])
In [21]: boys
Out[21]: {'Cooper': 493}
In [22]: girls
Out[22]: {'Ruby': 440}
|
Python TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
Question: I have looked into this before asking my question, but haven't been able to
find anything that fits in with my situation.
I'm writing a Python program - a text editor; using Python and Gtk+3.
Here is the error I'm getting:
Traceback (most recent call last):
File "file.py", line 58, in on_s_pressed
if (self.set_title == (filename + " - DeSedit")):
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
And here is my code:
#!/usr/bin/env python3
from gi.repository import Gtk, Gdk
class DeSedit(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="DeSedit")
self.set_default_size(650, 500)
# keyboard shortcuts
""" <Control>O """
accel = Gtk.AccelGroup()
accel.connect(Gdk.keyval_from_name('O'), Gdk.ModifierType.CONTROL_MASK, 0, self.on_o_pressed)
self.add_accel_group(accel)
""" <Control>S """
accel1 = Gtk.AccelGroup()
accel1.connect(Gdk.keyval_from_name('S'), Gdk.ModifierType.CONTROL_MASK, 0, self.on_s_pressed)
self.add_accel_group(accel1)
# grid to organize widgets
self.box = Gtk.Box()
self.add(self.box)
# text view
self.textview = Gtk.TextView()
self.textview.set_wrap_mode(True)
self.textbuffer = self.textview.get_buffer()
# scroll bar
scrollwindow = Gtk.ScrolledWindow()
scrollwindow.add(self.textview)
self.box.pack_start(scrollwindow, True, True, 0)
# open file dialog
def on_o_pressed(self, *args):
openDialog = Gtk.FileChooserDialog("Select file to be opened", self,
Gtk.FileChooserAction.OPEN,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
response = openDialog.run()
if response == Gtk.ResponseType.OK:
filename = openDialog.get_filename()
with open(filename, 'r') as fRead:
data = fRead.read()
self.textbuffer.set_text(data)
self.set_title(filename + " - DeSedit")
fRead.close()
openDialog.destroy()
elif response == Gtk.ResponseType.CANCEL:
openDialog.destroy()
# save file dialog
def on_s_pressed(self, *args):
saveDialog = Gtk.FileChooserDialog("Select folder to save file", self,
Gtk.FileChooserAction.SAVE,
(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
filename = saveDialog.get_filename()
if self.set_title == (filename + " - DeSedit"):
print("hmm")
response = saveDialog.run()
if response == Gtk.ResponseType.OK:
with open(filename, 'w') as fWrite:
data = self.textbuffer.get_text(self.textbuffer.get_start_iter(),
self.textbuffer.get_end_iter(), True)
fWrite.write(data)
fWrite.close()
saveDialog.destroy()
elif response == Gtk.ResponseType.CANCEL:
saveDialog.destroy()
window = DeSedit() # create DeSedit object
window.connect("delete-event", Gtk.main_quit)
window.show_all()
Gtk.main()
Answer: It basically tells you `filename` is a NoneType object, which means
`saveDialog.get_filename()` returnded `None`.
According to [the doc](http://www.pygtk.org/pygtk2reference/class-
gtkfilechooser.html#method-gtkfilechooser--get-filename) this means no file
was selected
> gtk.FileChooser.get_filename
>
> def get_filename()
>
> Returns : The currently selected filename, or None if no file is >selected,
> or the selected file can't be represented with a local filename.
|
Python 2.7 : global with imported modules
Question: In Python 2.7, depending on how I import a module, global variables can become
unreachable.
I have a file test.py which contains the following:
x = None
def f():
global x
x = "hello"
print x
I get the following expected behavior:
>>> import test
>>> print test.x
None
>>> test.f()
hello
>>> print test.x
hello
But now if i do an ugly 'import *' instead, i get the follwoing:
>>> from test import *
>>> print x
None
>>> f()
>>> print x
None
So variable x is no longer accessible.. Any clues ?
thanks, y
Answer: `from test import *` will do the equivalent of `x = test.x`. If you change
`test.x` later (which your call to `foo()` will do), it will not change the
copy of x in your local namespace.
|
Interrupts with Raspberry Pi and PiFace Digital
Question: I have just set up a Raspberry Pi with the PiFace Digital element14 I/O board.
So far, I've followed several steps to get it working such that I can
interface with the I/O ports (control the LED's and operate the switches to do
stuff) The python code I wrote works fine and I can make it do stuff.
Currently I'm just messing around, getting the feel for programming on the Pi,
and trying to get an understanding for the features. I wanted to set-up a
state machine for a simple 6-bit binary counter which counts up and down when
I tell it to, which I was able to do pretty easily. But when I tried to take
it to the next level and use interrupts for setting the state I ran into
issues.
I followed the
[Manual](https://media.readthedocs.org/pdf/pifacedigitalio/latest/pifacedigitalio.pdf)
as well as [This Guide](http://blog.oddbit.com/2013/08/05/interrupts-on-the-
pi/) to get the code for activating the interrupts.
The code I wrote executes without error, however, either the interrupts are
not detected or they don't do anything, I'm not sure which. My code is below.
I know that the while loop works for the 'waiting' and 'counting' states
because I can define the initial condition. It counts properly, so I feel
pretty sure that the while loop is okay, there's just no state changes.
import pifacedigitalio as pfio
import os
import time
def startCounter(event):
global state
state = 'counting'
print('counter started')
def stopCounter(event):
global state
state = 'waiting'
def stopProg(event):
global state
state = 'stop'
def resetCounter(event):
global state
state = 'reset'
def setLEDs(stateArray):
i = 0
for state in stateArray:
pfio.digital_write(i,state)
i = i + 1
def calcBools(count):
binString = bin(count).rsplit('0b')[1]
stringLength = len(binString)
zeroString = '0' * (8 - stringLength)
newString = zeroString + binString
i = 0
boolsOut = [0,0,0,0,0,0,0,0]
for bit in newString:
if bit == '1':
boolsOut[i] = 1
i = i + 1
return boolsOut
####################
### MAIN PROGRAM ###
####################
pfio.init()
pifacedigital = pfio.PiFaceDigital()
listener = pfio.InputEventListener(chip=pifacedigital)
signalDirection = pfio.IODIR_RISING_EDGE
listener.register(0, signalDirection, stopProg)
listener.register(1, signalDirection, startCounter)
listener.register(2, signalDirection, stopCounter)
listener.register(3, signalDirection, resetCounter)
listener.activate()
counter = 0
running = True
state = 'waiting'
setLEDs([0,0,0,0,0,0,0,0])
direction = 'up'
while(running):
if state == 'stop':
running = False
listener.deactivate()
counter = 0
elif state == 'waiting':
time.sleep(1)
print('waiting...')
elif state == 'counting':
if direction == 'up':
counter = counter + 1
else:
counter = counter - 1
if counter > 63:
direction = 'down'
elif counter == 0:
direction = 'up'
elif state == 'reset':
counter = 0
else:
time.sleep(0.1)
setLEDs(calcBools(counter))
print(counter)
time.sleep(0.25)
So this code doesnt work, and I tried something else which also didnt work
using the pifacecommon library, replacing some of the lines of code with:
import pifacecommon as pfc
readport = pfc.mcp23s17.GPIOA # I also tried GPIOB to no avail
listener = pfc.interrupts.PortEventListener(readport, 0)
After this the listener commands are identical for both methods. Along with
this I attempted to use the pfc.mcp23s17.write command, but apparently it
didn't exist or some foolish excuse like that.
Thanks in advance for reading this and even more if you respond, and more yet
if you have an answer for me!
-Ben
Edit (SOLVED): My answer was in the comments of the 2nd link i provided the
whole time :( Turns out I had everything written correctly, I just needed to
run the file from the terminal and not IDLE3.
Answer: So the answer to my question was in the comments of the [2nd
link](http://blog.oddbit.com/2013/08/05/interrupts-on-the-pi/) I provided the
entire time. All I needed to do was run the program from the terminal, and not
IDLE3.
I believe the reason lies in how interrupts are handled within Linux. Linux
ISR's aren't true ISR's, the processor puts the ISR in a sleep mode until it's
called. Can anyone elaborate on why IDLE3 doesn't support interrupts?
|
Python string search - starting from a specific position within a string
Question: I have the following text stored in a variable which has additional text
before and after it:
`'content="80.96"abcd'`
I have a search variable from which I find out the location of: content="
But then I need another search to find the location of the second quotation
mark, using the end position which I found out from the previous search as the
starting point for this second search. Is it possible to do that kind of
search, from a certain starting position in a string, using re.search?
You see, my goal is to get the 80.96, the price of some stock. However, for
another stock, it could be fewer or greater number of digits. My ultimate goal
is to search for the position of the second " so that I can calculate the
length of the stock price and extract it.
Using Python 3.4.3
Thanks
Answer: If I understand you question correctly. You just want to get the decimal from
the string. Assuming that all strings are of the same format i.e.
`content="<decimal>"cccc`.
You can split the string and then use a regex to do that:
In [1]: a = 'content="80.96"abcd'
In [2]: a.split('=')
Out[2]: ['content', '"80.96"abcd']
In [3]: b = a.split('=')[1]
In [4]: b
Out[4]: '"80.96"abcd'
In [5]: import re
In [6]: p = re.compile(ur'\"(\d*\.?\d*)\"')
In [7]: re.search(p, b)
Out[7]: <_sre.SRE_Match at 0x3ad2af8>
In [8]: obj = re.search(p, b)
In [9]: obj.group()
Out[9]: '"80.96"'
In [10]: s = obj.group()
In [11]: s
Out[11]: '"80.96"'
In [12]: s[1 : -1]
Out[12]: '80.96'
As a program it would be:
import re
def getDecimal(string):
part_2 = string.split('=')[1]
pattern = re.compile(ur'\"(\d*\.?\d*)\"')
obj = re.search(pattern, part_2)
return obj.group()[1 : -1]
print(getDecimal('content="83520.96652"asdf')) # Output: 83520.96652
|
How/where to use os.path.sep?
Question: `os.path.sep` is the character used by the operating system to separate
pathname components.
But when `os.path.sep` is used in `os.path.join()`, why does it truncate the
path?
Example:
Instead of `'home/python'`, `os.path.join` returns `'/python'`:
>>> import os
>>> os.path.join('home', os.path.sep, 'python')
'/python'
I know that
[`os.path.join()`](https://docs.python.org/2/library/os.path.html#os.path.join)
inserts the directory separator implicitly.
Where is `os.path.sep` useful? Why does it truncate the path?
Answer: > Where os.path.sep is usefull?
I suspect that it exists mainly because a variable like this is required in
the module anyway (to avoid hardcoding), and if it's there, it might as well
be documented. Its documentation says that it is ["occasionally
useful"](https://docs.python.org/2/library/os.html#os.sep).
> Why it truncates the path?
From the [docs for
`os.path.join()`](https://docs.python.org/2/library/os.path.html#os.path.join):
> If a component is an absolute path, all previous components are thrown away
> and joining continues from the absolute path component.
and `/` is an absolute path on *nix systems.
|
I want to store the Python shell data into a database
Question: I am new to Python. I'm using this code to get the details of a user (in a
Python shell currently).
import tweepy
import time
import sqlite3
import os
from datetime import datetime
auth = tweepy.OAuthHandler(key,secret)
auth.set_access_token(access_token, access_secter)
api = tweepy.API(auth)
user = api.get_user('<the_user_to_query_on_here>')
print ("User id: " + user.id_str)
print ("Screen_Name: " + user.screen_name)
print (user.name)
print ("Description: " + user.description)
print ("Language: " + user.lang)
print ("Account created at: " + str(user.created_at))
print ("Location: " + user.location)
print ("Time zone: " + user.time_zone)
print ("Number of tweets: " + str(user.statuses_count))
print ("Number of followers: " + str(user.followers_count))
print ("Number of Following: " + str(user.friends_count))
print ("A member of " + str(user.listed_count) + " lists.")
print ("Retreiving friends for", user.screen_name)
for friend in user.friends():
print ("Following_Names: " + str(friend.screen_name))
I would like to store this information in a database so that I can retrieve it
locally later. How do I do this?
Answer: You can use [SQLite3](https://docs.python.org/3.4/library/sqlite3.html) that's
already included in Python as a possible solution.
What you'll need to do, instead of calling `print()` to each one, assign it to
a variable, then store that variable into the database.
For example, change:
print ("User id: " + user.id_str)
print ("Screen_Name: " + user.screen_name)
to
user_id = user.id_str
screen_same = user.screen_name
Then open a connection to the database (before or after as long it doesn't
continously loop) and store those variables using:
import sqlite3 as lite
import sys
con = lite.connect('twitter.db')
with con:
cur = con.cursor()
# the following line only needed once to create the table
cur.execute("CREATE TABLE Twitter(User ID, Screen Name, etc...)")
cur.execute("INSERT INTO Twitter VALUES(user_id,screen_name, etc...)")
# or
# you can insert user.id_str directly without assigning it to a variable
# cur.execute("INSERT INTO Twitter VALUES(user.id_str,user.screen_name, etc...)")
Here's a great [tutorial](http://zetcode.com/db/sqlitepythontutorial/) about
SQLite3
|
There was a error importing one of the Python modules
Question: I am trying to run a yum command `# yum install mod-pagespeed` but I am
getting this error
> There was a problem importing one of the Python modules required to run yum.
> The error leading to this problem was:
>
> cannot import name Repository
>
> Please install a package which provides this module, or verify that the
> module is installed correctly.
>
> It's possible that the above module doesn't match the current version of
> Python, which is: 2.6.6 (r266:84292, Feb 22 2013, 00:00:18) [GCC 4.4.7
> 20120313 (Red Hat 4.4.7-3)]
>
> If you cannot solve this problem yourself, please go to the yum faq at:
> <http://yum.baseurl.org/wiki/Faq>
Your help will be greatly appreciated
Answer: Did you upgrade the Python that's running on your system? It's possible that
it broke yum, as yum on older systems relied on the Python version being 2.4
Can you downgrade python back to 2.4 to get yum working again, then do an
alternate install of Python to a newer version, keeping both on your system?
See this link for procedures for installing alternate versions of python:
<https://github.com/h2oai/h2o-2/wiki/Installing-python-2.7-on-
centos-6.3.-Follow-this-sequence-exactly-for-centos-machine-only>
|
Python merging two lists with all possible permutations
Question: I'm trying to figure out the best way to merge two lists into all possible
combinations. So, if I start with two lists like this:
list1 = [1, 2]
list2 = [3, 4]
The resulting list will look like this:
[[[1,3], [2,4]], [[1,4], [2,3]]]
That is, it basically produces a list of lists, with all the potential
combinations between the two.
I've been working through itertools, which I'm pretty sure holds the answer,
but I can't come up with a way to make it act this way. The closest I came
was:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
print list(itertools.product(list1, list2))
Which produced:
[(1, 5), (1, 6), (1, 7), (1, 8), (2, 5), (2, 6), (2, 7), (2, 8), (3, 5), (3, 6), (3, 7), (3, 8), (4, 5), (4, 6), (4, 7), (4, 8)]
So it does all the possible combinations of items in each list, but not all
the possible resulting lists. How do I get that to happen?
EDIT: The end goal is to be able to individually process each list to
determine efficiency (the actual data I'm working with is more complex). So,
in the original example above, it would work something like this:
list1 = [1, 2]
list2 = [3, 4]
Get first merged list: [[1,3], [2, 4]]
Do stuff with this list
Get second merged list: [[1,4], [2, 3]]
Do stuff with this list
If I got the "list of lists of lists" output I described above, then I could
put it into a for loop and process on. Other forms of output would work, but
it seems the simplest to work with.
Answer: `repeat` the first list, `permutate` the second and `zip` it all together
>>> from itertools import permutations, repeat
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> list(list(zip(r, p)) for (r, p) in zip(repeat(a), permutations(b)))
[[(1, 4), (2, 5), (3, 6)],
[(1, 4), (2, 6), (3, 5)],
[(1, 5), (2, 4), (3, 6)],
[(1, 5), (2, 6), (3, 4)],
[(1, 6), (2, 4), (3, 5)],
[(1, 6), (2, 5), (3, 4)]]
**EDIT** : As Peter Otten noted, the inner `zip` and the `repeat` is
superfluous.
[list(zip(a, p)) for p in permutations(b)]
|
python how to return to the start of the code
Question: I'm fairly new to python 3 but I'm making a simple program where I can select
the class of a pupil and choose to display their scores based on
averages,highest score etc... what I would like to know is how I can return to
the start of the code so I can select another class and chceck another set of
information eg. Class B-average score.I would like to know how I could return
to the start of the code. Thanks for your time I appreciate it.
Note I cut of part of the code
import csv
print("1 for Class A\n2 for Class B\n3 for Class C")
choosen=int(input())
class_a = open('class_a.txt')
class_b = open('class_b.txt')
class_c = open('class_c.txt')
if choosen == 1:
print("1 for for alphabetical orderwith each students highest score\n2 for highest score, highest to lowest\n3 for average score, highest to lowest")
cho_two=int(input())
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
row[3] = int(row[3])
row[4] = int(row[4])
row[5] = int(row[5])
minimum = min(row[3:5])
row.append(minimum)
maximum = max(row[3:5])
row.append(maximum)
average = sum(row[3:5])//3
row.append(average)
a_list.append(row[0:9])
if cho_two == 1:
alphabetical = [[x[0],x[6]] for x in a_list]
print("\nCLASS A\nEach students highest by alphabetical order \n")
for alpha_order in sorted(alphabetical):
print(alpha_order)
class_a.close()
elif cho_two == 2:
print("\nCLASS A\nThe highest score to the lowest \n")
for high_scr in sorted(highest_score,reverse = True):
print(high_scr)
class_a.close()
elif cho_two == 3:
average_score = [[x[8],x[0]] for x in a_list]
print("\nCLASS A\nThe average score from highest to lowest \n")
for ave_scr in sorted(average_score,reverse = True):
print(ave_scr)
class_a.close()
Example of the code running
1 for Class A
2 for Class B
3 for Class C
1
1 for for alphabetical orderwith each students highest score
2 for highest score, highest to lowest
3 for average score, highest to lowest
1
CLASS A
Each students highest by alphabetical order
['Bob', 2]
['Hamza', 6]
['James', 5]
['Jane', 0]
['John', 3]
['Kate', 3]
Answer: The commonly accepted way in Python is to use `while True:` to loop
indefinitely and then just use `break` when you want to exit the loop and end
the program (or continue with code you place outside the loop).
while True:
# Run code
if code_should_end:
break
Replace `if code_should_end` with what you want to trigger the end, whether
it's user input or something else. It also can be anywhere in your loop, it
doesn't need to just be at the end.
|
Check if post request logged me in
Question: I am trying to log in with a post request using the python requests module on
a MediaWiki page:
import requests
s = requests.Session()
s.auth = ('....', '....')
url = '.....'
values = {'wpName' : '....',
'wpPassword' : '.....'}
req = s.post(url, values)
print(req.content)
I can't tell from the return value of the post request whether the login
attempt was succesful. Is there something I can do to check this? Thanks.
Answer: Typically such an authentication mechanism is implemented using HTTP cookies.
You might be able to check for the existence of a session cookie after you've
authenticated successfully. You find the cookie in the HTTP response header or
the sessions cookie attribute `s.cookies`.
|
Conditional probability with sympy
Question: Since it is not a math related question but about using a library to do
symbolic computation, SO is better suited to answer this than
{math|stats}.stackexchange.com
I want to use Sympy to calculate the following:
[](http://i.stack.imgur.com/0U6nc.png)
This is the code I'm using in Sympy
from sympy.stats import Normal, density, DiscreteUniform, P, given
from sympy import Symbol, pprint, symbols, Symbol, Eq
sigma = Symbol("sigma", positive=True)
mu = DiscreteUniform('mu', [1,2])
N = Normal('normal', mu, sigma)
sampling_dist = given(N, Eq(mu, 1))
prior = P(Eq(mu, 1))
marginal = P(Eq(mu, 1))*given(N, Eq(mu, 1))+P(Eq(mu, 2))*given(N, Eq(mu,2))
post = prior * sampling_dist / marginal
Now I want to
1. be able to print the equation for the posterior distribution (I expect sigma and x to be the only unknown)
2. Plot the posterior by fixing sigma with a known value
I tried to print the equation by asking the density with
density(post)(Symbol('x'))
And I get the following error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-9b0e1c9ada72> in <module>()
----> 1 density(post)(Symbol('x'))
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in density(expr, condition, evaluate, numsamples, **kwargs)
692 **kwargs)
693
--> 694 return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
695
696
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in doit(self, evaluate, **kwargs)
643 isinstance(pspace(expr), SinglePSpace)):
644 return expr.pspace.distribution
--> 645 result = pspace(expr).compute_density(expr, **kwargs)
646
647 if evaluate and hasattr(result, 'doit'):
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in pspace(expr)
430 return rvs[0].pspace
431 # Otherwise make a product space
--> 432 return ProductPSpace(*[rv.pspace for rv in rvs])
433
434
/Users/alexis/anaconda3/lib/python3.4/site-packages/sympy/stats/rv.py in __new__(cls, *spaces)
278 # Overlapping symbols
279 if len(symbols) < sum(len(space.symbols) for space in spaces):
--> 280 raise ValueError("Overlapping Random Variables")
281
282 if all(space.is_Finite for space in spaces):
ValueError: Overlapping Random Variables
Even if I subs sigma with a constant I get the same error. I (obviouslu) don't
understand what I'm doing wrong.
Answer: I don't fully understand what you're trying to accomplish, but I ran your code
in a Jupyter notebook and examined the output of `post` with
sympy.init_printing() enabled, which displays the following:
[](http://i.stack.imgur.com/SeHGo.png)
The exception that gets thrown, `ValueError: Overlapping Random Variables`,
suggests that SymPy simply doesn't know what to do with the expression. I
suggest you double-check the construction of your expression, testing the
output in a more piecemeal way.
|
Combining matplotlib's mouse button events with pick events
Question: Based on combination of mouse button and key events, different functionalities
are applied to the points of a scatter plot. When the left mouse button is
pressed matplotlib's
[Lasso](http://matplotlib.org/examples/event_handling/lasso_demo.html) widget
is called and with the included points functionality 1 takes place. When
`Shift+LMB` are pressed a `Lasso` is drawn and functionality 2 takes place
with the included points. When `Alt+LMB` are pressed a `Lasso` is drawn and
with the included points functionality 3 takes place. Last, but not least,
when I press the `RMB` a pick event is triggered and the index of the selected
point in the scatter plot is given.
Since I added the `pick` event, the aforementioned functionalities work
correctly until a `pick` event is triggered for the **first time**. When it is
triggered it seems that the canvas gets locked and I can not use any other
functionality. Although, I get the index of the selected point, I do not get
any errors, and the canvas becomes unresponsive.
I modified the code taken from
[this](http://stackoverflow.com/questions/32322090/combine-key-and-mouse-
button-events-in-wxpython-panel-using-matplotlib) question, which is actually
what I want to do.
**Code:**
import logging
import matplotlib
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class Datum(object):
colorin = colorConverter.to_rgba('red')
colorShift = colorConverter.to_rgba('cyan')
colorCtrl = colorConverter.to_rgba('pink')
colorout = colorConverter.to_rgba('blue')
def __init__(self, x, y, include=False):
self.x = x
self.y = y
if include:
self.color = self.colorin
else:
self.color = self.colorout
class LassoManager(object):
def __init__(self, ax, data):
self.axes = ax
self.canvas = ax.figure.canvas
self.data = data
self.Nxy = len(data)
facecolors = [d.color for d in data]
self.xys = [(d.x, d.y) for d in data]
fig = ax.figure
self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100,),facecolors=facecolors, offsets = self.xys, transOffset = ax.transData)
ax.add_collection(self.collection)
self.pick=self.canvas.mpl_connect('pick_event', self.onpick)
self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
self.keyPress = self.canvas.mpl_connect('key_press_event', self.onKeyPress)
self.keyRelease = self.canvas.mpl_connect('key_release_event', self.onKeyRelease)
self.lasso = None
self.shiftKey = False
self.ctrlKey = False
def callback(self, verts):
logging.debug('in LassoManager.callback(). Shift: %s, Ctrl: %s' % (self.shiftKey, self.ctrlKey))
facecolors = self.collection.get_facecolors()
p = path.Path(verts)
ind = p.contains_points(self.xys)
for i in range(len(self.xys)):
if ind[i]:
if self.shiftKey:
facecolors[i] = Datum.colorShift
elif self.ctrlKey:
facecolors[i] = Datum.colorCtrl
else:
facecolors[i] = Datum.colorin
print self.xys[i]
else:
facecolors[i] = Datum.colorout
self.canvas.draw_idle()
self.canvas.widgetlock.release(self.lasso)
del self.lasso
def onpress(self, event):
if self.canvas.widgetlock.locked(): return
if event.inaxes is None: return
self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
# acquire a lock on the widget drawing
self.canvas.widgetlock(self.lasso)
def onKeyPress(self, event):
logging.debug('in LassoManager.onKeyPress(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = True
if event.key == 'shift':
self.shiftKey = True
def onKeyRelease(self, event):
logging.debug('in LassoManager.onKeyRelease(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = False
if event.key == 'shift':
self.shiftKey = False
def onpick(self,event):
if event.mouseevent.button == 3:
index = event.ind
print('onpick scatter:', index, np.take(x, index), np.take(y, index))
if __name__ == '__main__':
x,y =rand(2,100)
data = [Datum(*xy) for xy in zip(x,y)]
fig = plt.figure()
ax = plt.axes()
ax.scatter(x,y,picker=True)
lman = LassoManager(ax, data)
plt.show()
Any suggestions on what might be causing this malfunction? Thanks in advance.
Answer: The problem you're having this time is that you have both a `PickEvent` and a
`MouseEvent` that are generated at the same time when you click on an artist.
The `MouseEvent` locks the canvas and prevents you from doing anything else
afterward.
The best solution would be to prevent the `MouseEvent` from being fired after
the `PickEvent`, but I don't know if there's a way to do that. Instead, I
added a test to check whether `onpress()` was called after `onpick()` to
disable the locking mechanism.
import logging
import matplotlib
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import rand
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class Datum(object):
colorin = colorConverter.to_rgba('red')
colorShift = colorConverter.to_rgba('cyan')
colorCtrl = colorConverter.to_rgba('pink')
colorout = colorConverter.to_rgba('blue')
def __init__(self, x, y, include=False):
self.x = x
self.y = y
if include:
self.color = self.colorin
else:
self.color = self.colorout
class LassoManager(object):
def __init__(self, ax, data):
self.axes = ax
self.canvas = ax.figure.canvas
self.data = data
self.Nxy = len(data)
facecolors = [d.color for d in data]
self.xys = [(d.x, d.y) for d in data]
fig = ax.figure
self.collection = RegularPolyCollection(fig.dpi, 6, sizes=(100,),facecolors=facecolors, offsets = self.xys, transOffset = ax.transData)
ax.add_collection(self.collection)
self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
self.keyPress = self.canvas.mpl_connect('key_press_event', self.onKeyPress)
self.keyRelease = self.canvas.mpl_connect('key_release_event', self.onKeyRelease)
self.pick=self.canvas.mpl_connect('pick_event', self.onpick)
self.lasso = None
self.shiftKey = False
self.ctrlKey = False
self.pickEvent = False
def callback(self, verts):
logging.debug('in LassoManager.callback(). Shift: %s, Ctrl: %s' % (self.shiftKey, self.ctrlKey))
facecolors = self.collection.get_facecolors()
p = path.Path(verts)
ind = p.contains_points(self.xys)
for i in range(len(self.xys)):
if ind[i]:
if self.shiftKey:
facecolors[i] = Datum.colorShift
elif self.ctrlKey:
facecolors[i] = Datum.colorCtrl
else:
facecolors[i] = Datum.colorin
print self.xys[i]
else:
facecolors[i] = Datum.colorout
self.canvas.draw_idle()
self.canvas.widgetlock.release(self.lasso)
del self.lasso
def onpress(self, event):
logging.debug('in LassoManager.onpress(). Event received: %s' % event)
if self.pickEvent:
self.pickEvent = False
return
if self.canvas.widgetlock.locked(): return
if event.inaxes is None: return
self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
# acquire a lock on the widget drawing
self.canvas.widgetlock(self.lasso)
def onKeyPress(self, event):
logging.debug('in LassoManager.onKeyPress(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = True
if event.key == 'shift':
self.shiftKey = True
def onKeyRelease(self, event):
logging.debug('in LassoManager.onKeyRelease(). Event received: %s (key: %s)' % (event, event.key))
if event.key == 'alt':
self.ctrlKey = False
if event.key == 'shift':
self.shiftKey = False
def onpick(self, event):
logging.debug('in LassoManager.onpick(). Event received: %s' % event)
self.pickEvent = True
if event.mouseevent.button == 3:
index = event.ind
print 'onpick scatter: ', index, np.take(x, index), np.take(y, index)
if __name__ == '__main__':
x,y =rand(2,100)
data = [Datum(*xy) for xy in zip(x,y)]
fig = plt.figure()
ax = plt.axes()
ax.scatter(x,y,picker=True)
lman = LassoManager(ax, data)
plt.show()
|
How to make correct TCP request using python
Question: I am trying to make request but google.com returns status 400, but It should
be 302. What's wrong with my request? Do i need additional request header? Any
ideas?
Current code:
import socket
host = "www.google.com"
port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host,port))
client.send("GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n")
response = client.recv(4096)
print response
Response:
HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Content-Length: 1504
Date: Mon, 07 Sep 2015 16:25:02 GMT
Server: GFE/2.0
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
<title>Error 400 (Bad Request)!!1</title>
<style>
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/logos/errorpage/error_logo-150x54-2x.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
</style>
<a href=//w
ww.google.com/><span id=logo aria-label=Google></span></a>
<p><b>400.</b> <ins>That’s an error.</ins>
<p>Your client has issued a malformed or illegal request. <ins>That’s all we know.</ins>
Answer: In the string you use in the send function, you have missed a slash, when
specifying the HTTP protocol version.
client.send("GET / HTTP1.1\r\nHost: www.google.com\r\n\r\n")
should be:
client.send('GET / HTTP/1.1\r\nHost: www.google.com\r\n\r\n')
|
Python - import error in matplotlib raindrop example
Question: I'm trying to run [Nicolas Rougier's raindrop
animation](http://matplotlib.org/examples/animation/rain.html) using
`matplotlib` (version 1.4.3) on my Python 2.7.10 IDLE (running on a Mac, OS X
10.10.5) but am getting the following import error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
....
from matplotlib import pyplot as plt
File "/Library/Python/2.7/site-packages/matplotlib/pyplot.py", line 34, in <module>
from matplotlib.figure import Figure, figaspect
File "/Library/Python/2.7/site-packages/matplotlib/figure.py", line 40, in <module>
from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
File "/Library/Python/2.7/site-packages/matplotlib/axes/__init__.py", line 4, in <module>
from ._subplots import *
File "/Library/Python/2.7/site-packages/matplotlib/axes/_subplots.py", line 10, in <module>
from matplotlib.axes._axes import Axes
File "/Library/Python/2.7/site-packages/matplotlib/axes/_axes.py", line 21, in <module>
import matplotlib.dates as _ # <-registers a date unit converter
File "/Library/Python/2.7/site-packages/matplotlib/dates.py", line 126, in <module>
from dateutil.rrule import (rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY,
File "/Library/Python/2.7/site-packages/dateutil/rrule.py", line 16, in <module>
from six.moves import _thread
ImportError: cannot import name _thread
The script I'm using is exactly the same as in the link but I had to insert
the statements `import matplotlib` and `matplotlib.use('TKAgg')` before
`pyplot` and `FuncAnimation` import statements at the top.
Answer: You need to re-install the dateutil package for python.
sudo pip uninstall dateutil
sudo pip install python-dateutil==2.2
|
In Python, does `is not int` ever return false?
Question: I am using argument parser to allow passing port number to my program. I then
try to validate the value, and one of the first tests is the `is int` test:
parser = argparse.ArgumentParser(description='Provides XML-RPC API.')
parser.add_argument('--port', dest='port', default=9666, type=int,
help='port to listen on, 9666 by default.');
args = parser.parse_args()
if args.port is not int:
raise TypeError("Port must be integer (%s given), use -h argument to get help."%(type(args.port).__name__))
if args.port>=65536 or args.port<=0:
raise IndexError("Port must be lower than 65536, 65535 is the maximum port number. Also, port can only be positive, non-zero number. Use -h argument to get help.")
if args.port<=1204:
print("Notice: ports up to 1024 are reserved to well known services, using this port numbers often leads to conflicts. Use -h argument to get help.")
Now whatever I do, I get the error:
Port must be integer (int given), use -h argument to get help.
I mean, what the hell? Even the error says it was int, so what's going on?
Answer: `args.port is not int` will return `False` if `args.port` was ever set to the
`int` type:
args.port = int
args.port is int # True
or you re-bound `int` to the same object `args.port` already is bound to:
int = args.port
args.port is int # True
That is because `is` tests if two references are pointing to the exact same
object.
Perhaps you were confused on how to test for the type of an object, for that
you use the [`isinstance()`
function](https://docs.python.org/2/library/functions.html#isinstance), or
test the output of
[`type()`](https://docs.python.org/2/library/functions.html#type):
type(args.port) is not int # False if args.port is a different type
not isinstance(args.port, int) # False if args.port is a different type and not a subclass either
This will never be the case either, because you configured your
`ArgumentParser` option to only accept integers:
parser.add_argument('--port', dest='port', default=9666, type=int,
help='port to listen on, 9666 by default.')
The `type=int` argument is important, because that means that anything that
cannot be interpreted as an integer will be rejected by the parser. You will
never get past `parser.parse_args()` here:
>>> import argparse
>>> parser = argparse.ArgumentParser(description='Provides XML-RPC API.')
>>> parser.add_argument('--port', dest='port', default=9666, type=int,
... help='port to listen on, 9666 by default.')
_StoreAction(option_strings=['--port'], dest='port', nargs=None, const=None, default=9666, type=<type 'int'>, choices=None, help='port to listen on, 9666 by default.', metavar=None)
>>> parser.parse_args(['--port', 'not an integer'])
usage: [-h] [--port PORT]
: error: argument --port: invalid int value: 'not an integer'
That's because `'not an integer'` cannot be converted by the `int()` function;
a `ValueError` is raised and `argparse` translates that to an error message
for you:
>>> int('not an integer')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not an integer'
You could supply your own conversation function that limits the range:
def portnumber(value):
port = int(value) # may raise ValueError
if not 0 <= port <= 65536:
raise ValueError('Not a valid port number')
return port
Then use that as the `type`:
parser.add_argument('--port', dest='port', default=9666, type=portnumber,
help='port to listen on, 9666 by default.')
|
SSH identity key ignored when using gitpython under supervisor
Question: I have a simple Flask app that waits for webhooks from my repository host. The
webhook triggers a `git.pull()` of the latest revision from a predefined
repository using `gitpython`. The `gitpython` code is something like:
import git
repo_dir = '/path/to/repo'
g = git.cmd.Git(repo_dir)
g.pull()
The app is started with a supervisor script as a user, `admin`, whose ssh
`id_rsa.pub` public key is registered with the repository as a deployment key.
When logged in as the registered user, `admin`, the app can be started from
the command line and can successfully pull from the private repository. When
the app is started with `supervisor`, however, the `git.pull()` operation
fails with a ssh auth error:
`Permission denied (publickey). fatal: Could not read from remote repository.`
I can confirm the user launching the `supervisor` managed app is correct
(`admin`). This indicates that the supervisor script is not using the default
SSH key for the same user.
I have seen some reference to setting one of several environment variables,
`GIT_SSH_COMMAND` or a legacy `GIT_SSH`. I have tried setting these values to
both replacement ssh strings (ie `GIT_SSH_COMMAND='ssh -i /path/to/key'`) and
to executable files (ie `GIT_SSH='/path/to/myssh'`), but to no avail.
Has anyone encountered something like this? It's an unexpected problem, that I
am having trouble debugging.
Answer: Have you tried:
import git
repo_dir = '/path/to/repo'
g = git.cmd.Git(repo_dir)
g.USE_SHELL = True
g.pull()
|
Python 3.4 - how to get properties of an open window (size, position on screen e.t.c) and gui automation
Question: Python 3.4 . I want to get the properties of an open window (size, position on
screen e.t.c) if possible. is there an easy way to do this?. Also is there a
good module for simulating mouse clicks and key presses in an open application
Answer: if you using _tkinter_ , one of the most common GUI packet, then:
from Tkinter import *
root=Tk()
root.geometry('400x600')
root.update()
print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_x())
print (root.winfo_y())
root.mainloop()
you can replace:
print (root.winfo_width())
print (root.winfo_height())
print (root.winfo_x())
print (root.winfo_y())
with:
print (root.winfo_geometry())
|
Reading and writing CSV files into a data structure suitable for Excel-style column/row manipulations
Question: So I am currently working on a web-application with a few other people for a
client, and we've hit a stumbling block. Basically we need to be able to
upload a CSV file in a specific layout - and the application will take that
CSV file and based on specific columns and their values, it will perform the
algorithm and calculations required.
The output would also be a downloadable CSV file. None of us have had
experience working with CSV in Python.
The layout of the CSV file is as follows: ID, Name, Address, Suburb, Postcode,
Email, Phone
I need to take the address fields and use that in a calculation to determine
how to get to the destination from their specific address. I would also need
to print the specific details related to that person as well.
**EDIT** Okay so basically, the CSV file will contain details about employees
and their relevant personal information. What our application does is takes
that information, and based on the employees address, will predict the most
optimised route for them to get to the destination. Basically how the hell do
I read CSV files and then write an algorithm based on a certain column/row to
perform my calculations required.
Answer: Reading a `.csv` is easy with the
[csv](https://docs.python.org/2/library/csv.html) standard library module.
A more efficient library that allows for better manipulation of `.csv` files
is [pandas](http://pandas.pydata.org/), you should consider playing around
with this one first.
For instance, given a csv file:
csv = r"""col1,col2,col3,col4
bar,20150301,homer,53
foo,20150502,bart,102
barfoo,20150201,lisa,13
foobar,20150501,marge,97"""
We can operate on it with the `csv` module:
import csv # built-in no need to install
from StringIO import StringIO
with open(StringIO(csv), 'rb') as f:
reader = csv.reader(f)
for row in reader:
# Do whatever you need
And, similarly, with pandas:
import pandas as pnd # external, installation required
# returns a dataframe, specify cols, index et cetera
df = pnd.read_csv(StringIO(csv),
header=0,
index_col=["col1", "col3"],
usecols=["col1", "col2", "col3"],
parse_dates=["col2"])
# do dirty things with it.
|
How to get the Tor ExitNode IP with Python and Stem
Question: I'm trying to get the external IP that Tor uses, as mentioned
[here](http://stackoverflow.com/questions/9777192/how-do-i-get-the-tor-exit-
node-ip-address-over-the-control-port). When using something like
myip.dnsomatic.com, this is very slow. I tried what was suggested in the
aforementioned link (python + stem to control tor through the control port),
but all you get is circuit's IPs with no assurance of which one is the one on
the exitnode, and, sometimes the real IP is not even among the results.
Any help would be appreciated.
Also, from [here](http://stackoverflow.com/questions/1096379/tor-with-python),
at the bottom, Amine suggests a way to renew the identity in Tor. There is an
instruction, **controller.get_newnym_wait()** , which he uses to wait until
the new connection is ready (controller is from Control in steam.control),
isn't there any thing like that in Steam (sorry, I checked and double/triple
checked and couldn't find nothing) that tells you that Tor is changing its
identity?
Answer: You can use this code for check current IP (change SOCKS_PORT value to yours):
import re
import stem.process
import requesocks
SOCKS_PORT = 9053
tor_process = stem.process.launch_tor()
proxy_address = 'socks5://127.0.0.1:{}'.format(SOCKS_PORT)
proxies = {
'http': proxy_address,
'https': proxy_address
}
response = requesocks.get("http://httpbin.org/ip", proxies=proxies)
print re.findall(r'[\d.-]+', response.text)[0]
tor_process.kill()
|
trouble when using coords function in python tkinter canvas to modify object coordinates
Question: I am trying to make a canvas with some items that can move and rotate, to do
this, i have functions to modify the coordinates, however i am having trouble
with moving the objects. I am trying to use the coords function to change the
coordinates of each object.
the current bit of code that is raising the error is:
count = 1
for part in self._createdpartlist:
self.coords(part, self._partlist[count].coordinates)
count += 1
self is a Canvas object i created. with createdpartlist containing id's of
created parts in canvas (all 4 sided polygons) and partlist being a list of
objects that have coordinates that are returned in the form of [(x1, y1), (x2,
y2), (x3, y3), (x4, y4)]
however when i try to run it, i get the error;
_tkinter.TclError: bad screen distance "340)]"
(in this case 340 is the y4 coordinate)
I dont exactly know what it means by bad screen distance, and cant really
figure out whats going wrong or if i am using coords function incorrectly.
Any help is greatly appreciated
Edit: i get this error when i make a new file only containing this.
from tkinter import *
coordinates = [(330,230), (350,230), (350,340), (330,340)]
new_coords = [(340,245), (340,260), (400,260), (400,245)]
c = Canvas()
shape = c.create_polygon(coordinates)
c.coords(shape, new_coords)
the error comes up with "245)]" instead of "340)]" in this instance
Answer: Can you try this? I will try it later when I am not on mobile.
import itertools
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
# from itertools recipes: https://docs.python.org/2/library/itertools.html
def flatten(list_of_lists):
"""Flatten one level of nesting"""
return itertools.chain.from_iterable(list_of_lists)
coordinates = [(330,230), (350,230), (350,340), (330,340)]
new_coords = [(340,245), (340,260), (400,260), (400,245)]
c = tk.Canvas()
shape = c.create_polygon(coordinates)
c.coords(shape, *flatten(new_coords))
If that works then try:
for i, part in enumerate(self._createdpartlist):
self.coords(part, *flatten(self._partlist[i+1].coordinates))
|
Does eventlet do monkey_patch for threading module?
Question: Docs here in <http://eventlet.net/doc/patching.htm> says "If no arguments are
specified, everything is patched." and "thread, which patches thread,
threading, and Queue".
But with a simple test:
#!/bin/env python
import threading
import eventlet
eventlet.monkey_patch()
if __name__ == '__main__':
patched = eventlet.patcher.is_monkey_patched(threading)
print('patched : %s' % patched)
The result is:
patched : False
It seems like threading is not patched at all. The doc is wrong?
Answer: I found the doc is right. The problem is about is_monkey_patched(), it can't
detect some situation like 'threading, Queue' module. Take a look at the src
of this function, the behaviour is easy to understand.
def _green_thread_modules():
from eventlet.green import Queue
from eventlet.green import thread
from eventlet.green import threading
if six.PY2:
return [('Queue', Queue), ('thread', thread), ('threading', threading)]
if six.PY3:
return [('queue', Queue), ('_thread', thread), ('threading', threading)]
* * *
if on['thread'] and not already_patched.get('thread'):
modules_to_patch += _green_thread_modules()
already_patched['thread'] = True
* * *
def is_monkey_patched(module):
"""Returns True if the given module is monkeypatched currently, False if
not. *module* can be either the module itself or its name.
Based entirely off the name of the module, so if you import a
module some other way than with the import keyword (including
import_patched), this might not be correct about that particular
module."""
return module in already_patched or \
getattr(module, '__name__', None) in already_patched
And because the patch operation is implemented like this:
for name, mod in modules_to_patch:
orig_mod = sys.modules.get(name)
if orig_mod is None:
orig_mod = __import__(name)
for attr_name in mod.__patched__:
patched_attr = getattr(mod, attr_name, None)
if patched_attr is not None:
setattr(orig_mod, attr_name, patched_attr)
We can check whether a module like threading/Queue is patched by using:
>>>import threading
>>>eventlet.monkey_patch()
>>>threading.current_thread.__module__
>>>'eventlet.green.threading'
|
Every combination of list elements without replacement
Question: In Python 2.7 I'd like to get the [self-cartesian
product](http://stackoverflow.com/q/533905/2071807) of the elements of a list,
but without an element being paired with itself.
In[]: foo = ['a', 'b', 'c']
In[]: [x for x in itertools.something(foo)]
Out[]:
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
Currently I do:
[x for x in itertools.product(foo, repeat=2) if x[0] != x[1]]
but I suspect there's a built-in method for this. What is it?
_Note:`itertools.combinations` [wouldn't give
me](http://stackoverflow.com/a/5267969/2071807) `('a', 'b')` and `('b', 'a')`_
Answer: You are looking for
[permutations](https://docs.python.org/2/library/itertools.html#itertools.permutations)
instead of combinations.
from itertools import permutations
foo = ['a', 'b', 'c']
print(list(permutations(foo, 2)))
# Out: [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
|
Python Eve - POST payload containing a list
Question: I am having trouble with the `list` type in my schemas. Whenever I try to
POST, I get a 422 response stating 'must be of list type'. Below is a simple
example that produces this problem.
from eve import Eve
people = {
'schema': {
'tests': {
'type': 'list',
'schema': {
'type': 'string'
},
'required': True,
}
},
'resource_methods': ['GET', 'POST'],
}
settings = {
'DOMAIN': {
'people': people
}
}
app = Eve(settings=settings)
if __name__ == '__main__':
app.run()
Then when you POST to the people endpoint with the following:
import requests
url = "http://localhost:5000/people"
person = {
"tests": ['a', 'b'],
}
r = requests.post(url, data=person)
print(r.json())
You get the 422 response. When I debug this, it looks like the Eve application
has received the `tests` parameter as just a string, `'a'`, rather than the
whole list. From what I can see in the Eve tests on GitHub, this seems to be
the right way to make the request, so I can only assume I'm making a mistake
in setting up the resource/schema?
Thanks.
Answer: If you print `request.POST`, you would see `UnicodeMultiDict([('tests', u'a'),
('tests', u'b')])`. Fix to this would be to use `json object` for your `post`.
person = json.dumps({
"tests": ['a', 'b'],
})
r = requests.post(url, json=person)
print(r.json())
Or in your case, you will have to somehow tweak your POST request at API end
to get a list as:- `request.POST.getall('tests')` and then proceed.
Please check [using json in POST request](http://www.python-
requests.org/en/latest/user/quickstart/#more-complicated-post-requests). Also
while using `json`, json.dumps may not be required, the dictionary will be
`jsonified` automatically.
|
string.Formatter throws KeyError ''
Question: I want to print out key+value pairs like in [this
question](http://stackoverflow.com/q/28714510/5312756),
key a: 1
key ab: 2
key abc: 3
^ this colon is what I want
but I don't like the answer there and I tried to subclass `string.Formatter`
like this:
from __future__ import print_function
from string import Formatter
class KeyFormatter(Formatter):
def parse(self, fmtstr):
res = super(KeyFormatter, self).parse(fmtstr)
#for r in res:
# print(r)
return res
kf = KeyFormatter()
w = 10
x = dict(a=1, ab=2, abc=3)
for k in sorted(x):
v = x[k]
print(kf.format('key {::<{}} {}', k, w, v))
I want to debug the parsing to see if I can get at the extra '`:`' inserted in
the format string but this throws a
KeyError: '' in both Python 2.7 and 3.4. If I uncomment the for loop to see
what is going in the error goes away, but the final print statement then only
shows a newline.
When I make the last line:
print('key {:<{}} {}'.format(k, w, v))
this works (with spaces after the key), and when I do:
print('key {::<{}} {}'.format(k, w, v))
I get multiple ':' instead of spaces. But no KeyError.
Why do I get the `KeyError`? How can I debug this?
Answer: There are two somewhat related problems here, the simple answer to how to
debug is: you can't, at least not with print statements, or anything itself
using string formatting because that happens during another string format and
destroys the state of the formatter.
That it throws an error is caused by the fact that `string.Formatter()`
doesn't support empty fields, this was an addition to the formatting going
from 2.6 to 3.1 (and 2.7), which is in the C code, but not reflected in the
`string` module.
You can simulate the new behaviour by subclassing the class MyFormatter:
from __future__ import print_function
from string import Formatter
import sys
w = 10
x = dict(a=1, ab=2, abc=3)
if sys.version_info < (3,):
int_type = (int, long)
else:
int_type = (int)
class MyFormatter(Formatter):
def vformat(self, *args):
self._automatic = None
return super(MyFormatter, self).vformat(*args)
def get_value(self, key, args, kwargs):
if key == '':
if self._automatic is None:
self._automatic = 0
elif self._automatic == -1:
raise ValueError("cannot switch from manual field specification "
"to automatic field numbering")
key = self._automatic
self._automatic += 1
elif isinstance(key, int_type):
if self._automatic is None:
self._automatic = -1
elif self._automatic != -1:
raise ValueError("cannot switch from automatic field numbering "
"to manual field specification")
return super(MyFormatter, self).get_value(key, args, kwargs)
that should get rid of the `KeyError`. After that you should override the
`format_field` method instead of `parse`:
if sys.version_info < (3,):
string_type = basestring
else:
string_type = str
class TrailingFormatter(MyFormatter):
def format_field(self, value, spec):
if isinstance(value, string_type) and len(spec) > 1 and spec[0] == 't':
value += spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)
kf = TrailingFormatter()
w = 10
for k in sorted(x):
v = x[k]
print(kf.format('key {:t:<{}} {}', k, w, v))
and get:
key a: 1
key ab: 2
key abc: 3
Note the format specifier (`t`) that introduces the trailing character in the
format string.
The python formatting routines are actually smart enough to let you insert the
trailing character in the string just like the width formatting:
print(kf.format('key {:t{}<{}} {}', k, ':', w, v))
gives the same result and lets you dynamically change the '`:`'
You can also change `format_field` to be:
def format_field(self, value, spec):
if len(spec) > 1 and spec[0] == 't':
value = str(value) + spec[1] # append the extra character
spec = spec[2:]
return super(TrailingFormatter, self).format_field(value, spec)
and hand in any type:
print(kf.format('key {:t{}<{}} {}', (1, 2), '@', 10, 3))
to get:
key (1, 2)@ 3
but since you convert the value to a string before handing it to
`Formatter.formatfield()` that might get you a different result if `str(val)`
gets you a different value than using `{0}.format(val)` and/or with options
after `t:` that only apply to non-string types (such as `+` and `-`)
|
option mapping error with cfn-pyplates
Question: I am using cfn_pyplates to ingest a yaml file and spit out a json file but
have an issue with the option mapping of the cfn_pyplates here. I have this
particular piece of code at the start of the program. Now I have a yaml file
with “stack_role” in it which I used to access before with
options['stack_role’] and used to work successful but now throws the error :
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(sys.argv[1])))
from cfn_pyplates import core, functions
import djpp
stackName = options['stack_name']
resources = dict()
The error thrown:
> SBK-Kaul-PAR:cloudformation-private kaulk$ ./gen.sh dev/ testFile.yaml
> New python executable in python-virtualenv/bin/python Installing
> setuptools, pip...done. You are using pip version 6.1.1, however
> version 7.1.2 is available. You should consider upgrading via the 'pip
> install --upgrade pip' command. Requirement already satisfied (use
> --upgrade to upgrade): cfn-pyplates==0.4.3 in ./python-virtualenv/lib/python2.7/site-packages (from -r py_reqs.txt
> (line 3)) Traceback (most recent call last): File
> "/Users/kaulk/sandbox/cloudformation-private/python-virtualenv/bin/cfn_py_generate",
> line 10, in <module>
> sys.exit(generate()) File "/Users/kaulk/sandbox/cloudformation-private/python-virtualenv/lib/python2.7/site-packages/cfn_pyplates/cli.py",
> line 122, in generate
> pyplate = _load_pyplate(args['<pyplate>'], options_mapping) File "/Users/kaulk/sandbox/cloudformation-private/python-virtualenv/lib/python2.7/site-packages/cfn_pyplates/cli.py",
> line 40, in _load_pyplate
> exec pyplate in exec_namespace File "gen.py", line 5, in <module>
> import djpp File "/Users/kaulk/sandbox/cloudformation-private/djpp/__init__.py", line
> 1, in <module>
> from djpp import ec2, cloudformation, elb, inject File "/Users/kaulk/sandbox/cloudformation-private/djpp/cloudformation.py",
> line 1, in <module>
> import inspect, gen File "/Users/kaulk/sandbox/cloudformation-private/gen.py", line 7, in
> <module>
> stackName = options['stack_name'] NameError: name 'options' is not defined
Answer: found it, i was importing options in a different file which was causing this
issue. Thanks.
|
Convert from mac address to hex string and vice versa - both python 2 and 3
Question: I have MAC address that I want to send to dpkt as raw data. dpkt package
expect me to pass the data as hex stings. So, assuming I have the following
mac address: `'00:de:34:ef:2e:f4'`, written as: `'00de34ef2ef4'` and I want to
encode in to something like `'\x00\xdeU\xef.\xf4'` and the backward
translation will provide the original data.
On Python 2, I found couple of ways to do that using `encode('hex')` and
decode('hex'). However this solution isn't working for Python 3.
I'm haveng some trouble finding a code-snippet to support that on both
versions.
I'd appriciate help on this.
Thanks
Answer: [`binascii`
module](https://docs.python.org/3/library/binascii.html#binascii.hexlify)
works on both Python 2 and 3:
>>> import binascii
>>> binascii.unhexlify('00de34ef2ef4') # to raw binary
b'\x00\xde4\xef.\xf4'
>>> binascii.hexlify(_) # and back to hex
b'00de34ef2ef4'
>>> _.decode('ascii') # as str in Python 3
'00de34ef2ef4'
|
Using and modifying global variables across multiple modules in Python
Question: Python is my newest language (Python-2.6), my background is in C/C++.
Normally, I would create a global variable and be able to modify and access it
across all of my files. I am trying to achieve that same functionality in
python.
Based off of this post: [Python - Visibility of global variables in imported
modules](http://stackoverflow.com/questions/15959534/python-visibility-of-
global-variables-in-imported-modules) I see that "Globals in Python are global
to a module, not across all modules". I have multiple variables that rely on
user input, and must be accessed and modified by four different modules and in
the main code, which is why I am trying to use global(ish) variables in
Python.
I have two attemps to make this work:
1) If I stick the code with the modifiable global variables in my main code, I
run into the issue of "Executing the Main Module Twice" as detailed here:
<http://python-
notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html> The
program works, other than being executed twice.
2) If I create a separate module and put the variables into a function, I find
that I have undefined variables in my other modules and my code will error
out. From steping through the code, I see that when the variables are
accessible/modifiable by moduleA, but then everything breaks when moduleB and
moduleC try to use them, because the modifications did not stay.
How do I utilize Python to suit my needs? I believe my problem lies with
attempting to use global variables and importing the global variables
Answer: To solve this issue, I stopped trying to use global variables across multiple
modules in my main code and stopped importing individual variables. I
basically ended up placing moduleA(a single function) within moduleB. I
created a class within moduleB for the functions I needed. The main code and
moduleC now accesses those functions.
I still use global variables though, within the functions in moduleB. If I
made the variables not global I got attribute errors.
|
Unable to install mysqlclient in python3 virtualenv
Question: I want to run django with MySQL and Python 3. I initialized virtual
environment with `virtualenv --no-site-packages -p python3 ./`. Then I
installed django and wheel using pip, so pip freeze gives
django==1.8.3
wheel==0.24.0
Then I tried installing mysqlclient with `pip install mysqlclient`, but it
ended with
Downloading/unpacking mysqlclient
Downloading mysqlclient-1.3.6.tar.gz (78kB): 78kB downloaded
Running setup.py (path:/tmp/pip-build-jpdlrnc8/mysqlclient/setup.py) egg_info for package mysqlclient
Installing collected packages: mysqlclient
Running setup.py install for mysqlclient
building '_mysql' extension
i586-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,6,'final',1) -D__version__=1.3.6 -I/usr/include/mysql -I/usr/include/python3.4m -I/home/ondra/zelvovani/include/python3.4m -c _mysql.c -o build/temp.linux-i686-3.4/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DTAOCRYPT_DISABLE_X86ASM -g -DNDEBUG
error: command 'i586-linux-gnu-gcc' failed with exit status 1
Complete output from command /home/ondra/zelvovani/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-jpdlrnc8/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-fa_6nkh3-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/ondra/zelvovani/include/site/python3.4:
running install
running build
running build_py
creating build
creating build/lib.linux-i686-3.4
copying _mysql_exceptions.py -> build/lib.linux-i686-3.4
creating build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/compat.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-i686-3.4/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-i686-3.4/MySQLdb
creating build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-3.4/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-3.4/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-i686-3.4
i586-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,3,6,'final',1) -D__version__=1.3.6 -I/usr/include/mysql -I/usr/include/python3.4m -I/home/ondra/zelvovani/include/python3.4m -c _mysql.c -o build/temp.linux-i686-3.4/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DTAOCRYPT_DISABLE_X86ASM -g -DNDEBUG
error: command 'i586-linux-gnu-gcc' failed with exit status 1
----------------------------------------
Cleaning up...
Command /home/ondra/zelvovani/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-jpdlrnc8/mysqlclient/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-fa_6nkh3-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/ondra/zelvovani/include/site/python3.4 failed with error code 1 in /tmp/pip-build-jpdlrnc8/mysqlclient
Storing debug log for failure in /home/ondra/.pip/pip.log
I have installed `libmysqlclient-dev`, `python3-dev`, `zlib1g-dev` (packages
that were suggested in other questions here in stackoverflow).
Do you have any ideas, what am I doing wrong?
Answer: Use pymysql and it should solve your problem.Use `pip3 install pymysql`. After
installing , in file directory `project/project/__init__.py` write this
import pymysql
pymysql.install_as_MySQLdb()
Note:- project is the name of your django project.
|
wxPython threads blocking
Question: This is in the Phoenix fork of wxPython.
I'm trying to run a couple threads in the interests of not blocking the GUI.
Two of my threads work fine, but the other one never seem to hit its bound
result function. I can tell that it's running, it just doesn't seem to
properly post the event.
Here's the result function for the main calculation threads:
def on_status_result(self, event):
if not self.panel.progress_bar.GetRange():
self.panel.progress_bar.SetRange(event.data.parcel_count)
self.panel.progress_bar.SetValue(event.data.current_parcel)
self.panel.status_label.SetLabel(event.data.message)
Here's how I'm binding them:
from wx.lib.pubsub.core import Publisher
PUB = Publisher()
Here's how I'm binding the method:
def post_event(message, data):
wx.CallAfter(lambda *a: Publisher().sendMessage(message, data=data))
And here are the threads. The first one does not work, but the second two do:
class PrepareThread(threading.Thread):
def __init__(self, notify_window):
threading.Thread.__init__(self)
self._notify_window = notify_window
self._want_abort = False
def run(self):
while not self._want_abort:
for status in prepare_collection(DATABASE, self._previous_id, self._current_id, self._year, self._col_type,
self._lock):
post_event('prepare.running', status)
post_event('prepare.complete', None)
return None
def abort(self):
self._want_abort = True
class SetupThread(threading.Thread):
def __init__(self, notify_window):
threading.Thread.__init__(self)
self._notify_window = notify_window
self._want_abort = False
def run(self):
while not self._want_abort:
do_more_stuff_with_the_database()
return None
def abort(self):
self._want_abort = True
class LatestCollectionsThread(threading.Thread):
def __init__(self, notify_window):
threading.Thread.__init__(self)
self._notify_window = notify_window
self._want_abort = False
def run(self):
while not self._want_abort:
do_stuff_with_my_database()
return None
def abort(self):
self._want_abort = True
`prepare_collection` is a function that yields `Status` objects that looks
like this:
class Status:
def __init__(self, parcel_count, current_parcel, total, message):
self.parcel_count = parcel_count
self.current_parcel = current_parcel
self.total = total
self.message = message
Here's how I'm creating/starting/subscribing the PrepareThread:
MainForm(wx.Form):
prepare_thread = PrepareThread(self)
prepare_thread.start()
self.pub = Publisher()
self.pub.subscribe(self.on_status_result, 'prepare.running')
self.pub.subscribe(self.on_status_result, 'prepare.complete')
def on_status_result(self, event):
if not self.panel.progress_bar.GetRange():
self.panel.progress_bar.SetRange(event.data.parcel_count)
self.panel.progress_bar.SetValue(event.data.current_parcel)
self.panel.status_label.SetLabel(event.data.message)
I've tried stubbing out `prepare_collection` with `range(10)`, but I still
don't ever hit the event handler.
Answer: the problem is that the event system ends up calling the update function(event
handler) from the threads themselves , you should pretty much never do
that(basically you end up with strange race conditions and artifacts) ...
always make the callback in the main thread.
wxPython has taken this into consideration and any methods called with
wx.CallAfter will be called from the main program loop which is always running
in the main thread. this combined with the wx.pubsub module allow you to
create your own event frame work easily ... something like this
def MyPostEvent(event_name,event_data):
#just a helper that triggers the event with wx.CallAfter
wx.CallAfter(lambda *a:Publisher().sendMessage(event_name,data=event_data))
#then to post an event
MyPostEvent("some_event.i_made_up",{"payload":True})
#then in your main thread subscribe
def OnEventHandler(evt):
print "EVT.data",evt.data
pub = Publisher()
pub.subscribe("some_event.i_made_up",OnEventHandler)
|
TCP Proxy Using Python
Question: I am studying [Black Hat Python](https://www.nostarch.com/blackhatpython) and
trying to understand the TCP proxy code.
I now almost understand it, but it doesn't quite work when I try to test it
with
python proxy.py localhost 21 ftp.target.ca 21 True
in one terminal and
ftp ftp.target.ca 21
in another.
In the first terminal, I get only listen on localhost on port 21 and nothing
else; and in the second terminal, it's happen connection between me and server
and I wrote username and password.
The packages that transfer between me and server should appear in the first
terminal.
What am I doing wrong?
Here is the code:
import sys
import socket
import threading
# this is a pretty hex dumping function directly taken from
# http://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(src, length=16):
result = []
digits = 4 if isinstance(src, unicode) else 2
for i in xrange(0, len(src), length):
s = src[i:i+length]
hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
result.append( b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text) )
print b'\n'.join(result)
def receive_from(connection):
buffer = ""
# We set a 2 second time out depending on your
# target this may need to be adjusted
connection.settimeout(2)
try:
# keep reading into the buffer until there's no more data
# or we time out
while True:
data = connection.recv(4096)
if not data:
break
buffer += data
except:
pass
return buffer
# modify any requests destined for the remote host
def request_handler(buffer):
# perform packet modifications
return buffer
# modify any responses destined for the local host
def response_handler(buffer):
# perform packet modifications
return buffer
def proxy_handler(client_socket, remote_host, remote_port, receive_first):
# connect to the remote host
remote_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote_socket.connect((remote_host,remote_port))
# receive data from the remote end if necessary
if receive_first:
remote_buffer = receive_from(remote_socket)
hexdump(remote_buffer)
# send it to our response handler
remote_buffer = response_handler(remote_buffer)
# if we have data to send to our local client send it
if len(remote_buffer):
print "[<==] Sending %d bytes to localhost." % len(remote_buffer)
client_socket.send(remote_buffer)
# now let's loop and reading from local, send to remote, send to local
# rinse wash repeat
while True:
# read from local host
local_buffer = receive_from(client_socket)
if len(local_buffer):
print "[==>] Received %d bytes from localhost." % len(local_buffer)
hexdump(local_buffer)
# send it to our request handler
local_buffer = request_handler(local_buffer)
# send off the data to the remote host
remote_socket.send(local_buffer)
print "[==>] Sent to remote."
# receive back the response
remote_buffer = receive_from(remote_socket)
if len(remote_buffer):
print "[<==] Received %d bytes from remote." % len(remote_buffer)
hexdump(remote_buffer)
# send to our response handler
remote_buffer = response_handler(remote_buffer)
# send the response to the local socket
client_socket.send(remote_buffer)
print "[<==] Sent to localhost."
# if no more data on either side close the connections
if not len(local_buffer) or not len(remote_buffer):
client_socket.close()
remote_socket.close()
print "[*] No more data. Closing connections."
break
def server_loop(local_host,local_port,remote_host,remote_port,receive_first):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.bind((local_host,local_port))
except:
print "[!!] Failed to listen on %s:%d" % (local_host,local_port)
print "[!!] Check for other listening sockets or correct permissions."
sys.exit(0)
print "[*] Listening on %s:%d" % (local_host,local_port)
server.listen(5)
while True:
client_socket, addr = server.accept()
# print out the local connection information
print "[==>] Received incoming connection from %s:%d" % (addr[0],addr[1])
# start a thread to talk to the remote host
proxy_thread = threading.Thread(target=proxy_handler,args=(client_socket,remote_host,remote_port,receive_first))
proxy_thread.start()
def main():
# no fancy command line parsing here
if len(sys.argv[1:]) != 5:
print "Usage: ./proxy.py [localhost] [localport] [remotehost] [remoteport] [receive_first]"
print "Example: ./proxy.py 127.0.0.1 9000 10.12.132.1 9000 True"
sys.exit(0)
# setup local listening parameters
local_host = sys.argv[1]
local_port = int(sys.argv[2])
# setup remote target
remote_host = sys.argv[3]
remote_port = int(sys.argv[4])
# this tells our proxy to connect and receive data
# before sending to the remote host
receive_first = sys.argv[5]
if "True" in receive_first:
receive_first = True
else:
receive_first = False
# now spin up our listening socket
server_loop(local_host,local_port,remote_host,remote_port,receive_first)
main()
Answer: Simply running a proxy server on port 21 won't make the ftp client use it - so
you shouldn't be trying to connect to the remote host. if the commandline is
running the proxy on for example 9000, then ftp to that port i.e. localhost
9000 and the proxy will forward communication to/from that remote host.
|
MariaDB, pypyodbc, "Unknown prepared statement handler" executing "SELECT" query on table loaded with "LOAD DATA LOCAL INFILE."
Question: Python 3.4.3, MariaDB 10.0.21, MariaDB ODBC Connector 1.0.0, pypyodbc 1.3.3,
all 64-bit on 64-bit Windows 7.
I've got a python script that's supposed to create a table, populate it with
data from a fixed-width file, and then run a SELECT statement against it. All
simple stuff. My script looks something like this:
import pypyodbc
def do_stuff(name, password, filepath):
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
cursor.execute("CREATE TABLE `foo`.`bar` (`col1` INT);")
cursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE `foo`.`bar` (@row) SET col1 = SUBSTR(@row,1,1)" % filepath.replace("\\", "\\\\"))
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
print(row)
db.close()
do_stuff("root", "password", r"C:\\Users\\laj\\Desktop\\test.txt")
It grabs the first character from each line in the the text file and sticks it
in the sole column in the table. When the "SELECT" statement comes around,
however, I get hit with the following error:
Traceback (most recent call last):
File "test.py", line 25, in <module>
do_stuff("root", "oag123", r"C:\\Users\\laj\\Desktop\\test.txt")
File "test.py", line 21, in do_stuff
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1605, in execute
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1631, in execdirect
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 986, in check_success
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 964, in ctrl_err
pypyodbc.Error: ('HY000', '[HY000] Unknown prepared statement handler (5) given to mysqld_stmt_reset')
What really gets me, though is that I can get rid of the error simply by
closing and reopening the database connection in between populating the table
and executing the "SELECT," like so:
import pypyodbc
def do_stuff(name, password, filepath):
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
cursor.execute("CREATE TABLE `foo`.`bar` (`col1` INT);")
cursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE `foo`.`bar` (@row) SET col1 = SUBSTR(@row,1,1)" % filepath.replace("\\", "\\\\"))
db.close()
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
print(row)
db.close()
do_stuff("root", "password", r"C:\\Users\\laj\\Desktop\\test.txt")
Unfortunately, this isn't actually a valid solution to my problem. Not only is
it something I shouldn't have to do, but it also doesn't help when it comes to
temporary tables because they just get dropped during the disconnect phase of
that "fix." Any insight would be great, this is driving me up a wall.
Answer: `execute` does not return what you think:
cursor.execute("SELECT ...");
rows = cur.fetchall();
for row in rows ...
|
Vigenere cipher corrupts some
Question: I am making a simple vigenere cipher encrypter/decrypter in python, and it
works for the most part. I'm not getting any errors, but some letters aren't
encrypted or decrypted (or both?) properly. Here is my code:
import sys
if not len(sys.argv) == 4:
print "Not enough arguments."
print "Usage: python vigener.py <encrypt/decrypt> 'ciphertext' 'key'"
sys.exit()
mode = sys.argv[1]
ctext = sys.argv[2]
key = sys.argv[3]
if mode == "encrypt":
print "Encrypting using vigener cipher..."
elif mode == "decrypt":
print "Decrypting using vigener cipher..."
else:
print "Unknown function '"+str(mode)+"'."
print "Usage: python vigener.py <encrypt/decrypt> 'ciphertext' 'key'"
MAGIC_NUMBER = 96
ctext = ctext.lower()
repeated_key = ( key * (1+len(ctext)/len(key)) )[:len(ctext)]
if mode == "encrypt":
ctext = ctext.replace(" ", "{")
nums = [ord(ltr)-MAGIC_NUMBER for ltr in ctext]
rk_nums = [ord(ltr)-MAGIC_NUMBER for ltr in repeated_key]
enc_nums = [(num+rk_nums[ nums.index(num) ]) % 27 for num in nums]
enc_ltrs = [chr(num+MAGIC_NUMBER) for num in enc_nums]
print "".join(enc_ltrs)
elif mode == "decrypt":
enc_nums = [ord(ltr)-MAGIC_NUMBER for ltr in ctext]
rk_nums = [ord(ltr)-MAGIC_NUMBER for ltr in repeated_key]
dec_nums = [(num-rk_nums[ enc_nums.index(num) ]) for num in enc_nums]
dec_nums2 = [ (num + 27 if num < 1 else num) for num in dec_nums]
dec_ltrs = [chr(num+MAGIC_NUMBER) for num in dec_nums2]
dec_str = "".join(dec_ltrs)
dec_str = dec_str.replace("{", " ")
print "".join(dec_str)
and here is my terminal output:
$ python vigener.py encrypt 'this is confidential' 'secretkey'
Encrypting using vigener cipher...
lmljeljeagsiliyslltq
$ python vigener.py decrypt 'lmljeljeagsiliyslltq' 'secretkey'
Decrypting using vigener cipher...
thts ts conftfenttal
$
It seems to only encrypt/decrypt _some_ letters incorrectly. What the heck is
going on?
Answer: Short answer - these two lines need to be fixed:
enc_nums = [(x + y) % 27 for (x, y) in zip(nums, rk_nums)]
...
dec_nums = [(x - y) % 27 for (x, y) in zip(enc_nums, rk_nums)]
* * *
Long answer: The way your code uses `list.index()` is a logical error.
Suppose we're doing encryption, and the plaintext is `'banana'`, key is
`'secretkey'`. In the old code, this is what happens:
nums = [2, 1, 14, 1, 14, 1] # 'banana'
rk_nums = [19, 5, 3, 18, 5, 20] # 'secret'
enc_nums = [
( 2 + rk_nums[nums.index( 2)]) % 27,
( 1 + rk_nums[nums.index( 1)]) % 27,
(14 + rk_nums[nums.index(14)]) % 27,
( 1 + rk_nums[nums.index( 1)]) % 27,
(14 + rk_nums[nums.index(14)]) % 27,
( 1 + rk_nums[nums.index( 1)]) % 27 ]
We can elaborate on what happens with the list `enc_nums`:
enc_nums = [
( 2 + rk_nums[0]) % 27,
( 1 + rk_nums[1]) % 27,
(14 + rk_nums[2]) % 27,
( 1 + rk_nums[1]) % 27,
(14 + rk_nums[2]) % 27,
( 1 + rk_nums[1]) % 27 ]
The problem occurs when a letter occurs in the plaintext more than once. The
method `list.index()` returns the index of the first occurrence. Thus the
wrong index of the key (`rk_nums`) is used for encrypting the letters.
The easy solution is to use the
[`zip()`](https://docs.python.org/2/library/functions.html#zip) function,
which pairs up elements from both lists at the same index. For example,
`zip([9, 8, 7, 6], [0, 1, 2, 3])` will return the list `[(9,0), (8,1), (7,2),
(6,3)]`. This way, you can ensure that the plaintext numbers and key numbers
are used in sync all the time.
|
Python (Length input to draw star with a center point of 0,0)
Question: I have some code were the users input the length they want their star to be
and then it draws out the star. What I am trying to accomplish here, is that
every-time they make their input not only that it draws the star but it also
keeps it centered in the screen. so middle point 0,0
import turtle
Length = eval(input("enter the length you want for your star: "))
turtle.penup()
turtle.goto(0,200)
turtle.pendown()
turtle.goto(0,-200)
turtle.penup()
turtle.goto(200,0)
turtle.pendown()
turtle.goto(-200,0)
turtle.penup()
turtle.goto(0,0)
turtle.showturtle
turtle.pendown()
turtle.left(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
Answer: Try this
import turtle
import math
theta = 18 * math.pi / 180 # convert degrees to radians
Length = eval(input("enter the length you want for your star: "))
x = math.sin(theta) * Length
y = math.cos(theta)* Length / 2
turtle.penup()
turtle.goto(0,200)
turtle.pendown()
turtle.goto(0,-200)
turtle.penup()
turtle.goto(200,0)
turtle.pendown()
turtle.goto(-200,0)
turtle.penup()
#turtle.goto(0,0)
turtle.goto(x,-y)
turtle.showturtle
turtle.pendown()
turtle.left(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.right(36*4)
turtle.forward(Length)
turtle.hideturtle()
input("Press Enter to exit")
It's just a matter of figuring out the coordinates of the center of the star
you were drawing, and then translating the starting position by that vector,
to move the center to the origin.
EDIT:
If you go back to your original drawing, to the left of the y-axis, your see
two line segments, in an inverted V-shape. If we join the two intersections of
these segments with the x-axis to each other, we have an isosceles triangle
whose center is the center of the star. That's the point we need to find. Now,
each angle of the star is 36 degrees, and half that is 18. That's where the 18
comes from. To actually find the center, we need to use some trigonometry,
which I gather you haven't studied yet. The functions sin and cos are the sine
and cosine functions from trigonometry. The arguments to these functions are
usually given not in degrees, but in another system called radians. It happens
that 1800 degrees is the same as pi radians, so theta is just an 18 degree
angle, measured in radians.
"Why 18 degrees," did I hear you ask? Remember that we're try to find the
center of that isosceles triangle, with two side equal to length, and a
hypotenuse of Length. So, we I drop a perpendicular to the base, we cut it
into two right triangles, with one acute angle of 18 degrees (and the other 72
degrees.) And this is where the sine and cosine come in. In a right triangle
with hypotenuse Length, the side opposite an acute angle theta has length
`sin(theta)*Length` and the side adjacent to the angle theta has length
`cos(theta)*Length`.
This is a long-winded explanation, but I don't know how to make it shorter in
this format. You can find an explanation with pictures
[here](https://www.mathsisfun.com/algebra/trigonometry.html)
|
Python - Spyder gets hang while using Pandas DataFrame
Question: Recently I am facing serious issue with combination of spyder + pandas +
ipython.
I am using Spyder which is using iPython. I am trying following code which is
working well:
import pandas as pd
x = [list(range(5)) for i in range(1000)]
pd.DataFrame(x)
But when I assigned same DataFrame to variable of same or different name it
goes into hang phase (not coming out even after 30-45 minutes)
x = pd.DataFrame(x)
## OR
y = pd.DataFrame(x)
Same code is working well when I tried it in python console or ipython
console.
Following are the related packages I have installed on my system.
ipykernel 4.0.3 py27_0
ipython 4.0.0 py27_0
ipython-genutils 0.1.0 <pip>
ipython-notebook 4.0.4 py27_0
ipython-qtconsole 4.0.1 py27_0
ipython_genutils 0.1.0 py27_0
ipywidgets 4.0.2 py27_0
pandas 0.16.1 np19py27_0 (Also tried 0.16.2)
python 2.7.10 0
spyder 2.3.6 py27_0
spyder-app 2.3.6 py27_0
I am having Ubuntu 14.04 64 bit.
Let me know if you want more information.
Thanks Vishnu
Answer: This [has been reported as a bug in Spyder](https://github.com/spyder-
ide/spyder/issues/2744), a fix has been prepared, and it will be available in
the very next version. Right now I am using the workaround of calling it with
a dummy `column` argument.
|
Using BeautifulSoup to extract specific dl and dd list elements
Question: My first time posting. I am using BeautifulSoup 4 and python 2.7 (pycharm). I
have a webpage containing elements and I need to extract specific elements
where the tags are either 'Salary:' or 'Date:', the page contains multiple
lists .
The problem: I cannot seem to identify and extract specific text. I have
searched this site and tried without success.
Example html:
<dl><dt>Date:</dt><dd>13 September 2015</dd><dt>Salary:</dt><dd>Starting at £40,130 per annum.</dd></dl><dl><dt>Date:</dt><dd>15 December 2015</dd><dt>Salary:</dt><dd>Starting at £22,460 per annum.</dd></dl><dl><dt>Date:</dt><dd>10 January 2014</dd><dt>Salary:</dt><dd>Starting at £18,160 per annum.</dd></dl>
Code which I have tried without success:
r = requests.get("http://www.mywebsite.com/test.html")
soup = BeautifulSoup(r.content, "html.parser")
dl_data = soup.find_all("dl")
for dlitem in dl_data:
print dlitem.find("dt",text="Date:").parent.findNext("dd").contents[0]
print dlitem.find("dt",text="Salary:").parent.findNext("dd").contents[0]
Expected Result:
13 September 2015
15 December 2015
10 January 2014
Starting at £40,130 per annum.
Starting at £22,460 per annum.
Starting at £18,160 per annum.
Actual Result:
print dlitem.find("dt",text="Date:").parent.findNext("dd").contents[0]
AttributeError: 'NoneType' object has no attribute 'parent'
I have tried numerous variations of this code and gone round in circles, I
figured out how to print out all dd elements to screen, just not specific dd
elements!
Thanks
Answer: If order is not important just make some changes:
...
dl_data = soup.find_all("dd")
for dlitem in dl_data:
print dlitem.string
Result:
13 September 2015
Starting at £40,130 per annum.
15 December 2015
Starting at £22,460 per annum.
10 January 2014
Starting at £18,160 per annum.
For your latest request:
for item in list(zip(soup.find_all("dd")[0::3],soup.find_all("dd")[2::3])):
date, salary = item
print ', '.join([date.string, salary.string])
Output:
13 September 2015, 100
14 September 2015, 200
|
Multiple language datetime text to standard date format
Question: I'm using `dateutil.parser.parse` in Python to standardize dates. Not all of
the dates are in English. Therefore, the standardization process failed with
"unknown string format" error. Is there a way to process such dates or at
least avoid the error?
Sample date formats:
* Wed, 17 Oct 2001 11:49:53 -0700 (PDT)
* Wednesday, February 06, 2002 8:55 AM
* Domingo 25 de Noviembre de 2001 08:02
Answer: Can you use a different date parsing package? Maybe give
[dateparser](https://pypi.python.org/pypi/dateparser) a try?
Install using pip:
pip install dateparser
Example usage:
>>> import dateparser
>>> timestamp1 = "Wed, 17 Oct 2001 11:49:53 -0700 (PDT)"
>>> timestamp2 = "Wednesday, February 06, 2002 8:55 AM"
>>> timestamp3 = "Domingo 25 de Noviembre de 2001 08:02"
>>> dateparser.parse(timestamp1)
datetime.datetime(2001, 10, 17, 20, 49, 53)
>>> dateparser.parse(timestamp2)
datetime.datetime(2002, 2, 6, 8, 55)
>>> dateparser.parse(timestamp3)
datetime.datetime(2001, 11, 25, 8, 2)
dateparser documentation: <https://dateparser.readthedocs.org/en/latest/>
|
How do I write code to avoid error when windows service read config file?
Question: I have file tree:
f:/src/
restore.ini
config.py
log.py
service.py
test.py
the `test.py` code like this:
import service
import log
import config
class Test(object):
def __init__(self):
super(Test, self).__init__()
def setUp(self):
self.currentRound = int(config.read_config_co(r'restore.ini', 'Record')['currentRound'])
def testAction(self):
log.info(self.currentRound)
def tearDown(self):
config.write_config_update_co(self.currentRound-1, 'Record', 'currentRound', r'restore.ini')
class PerfServiceThread(service.NTServiceThread):
def run (self):
while self.notifyEvent.isSet():
try:
test = Test()
test.setUp()
test.testAction()
test.tearDown()
except:
import traceback
log.info(traceback.format_exc())
class PerfService(pywinservice.NTService):
_svc_name_ = 'myservice'
_svc_display_name_ = "My Service"
_svc_description_ = "This is what My Service does"
_svc_thread_class = PerfServiceThread
if __name__ == '__main__':
pywinservice.handleCommandLine(PerfService)
Now, I use cmdline `python test.py install` and `python test.py start` to
action service, but error.
If I move all files in directory `src` to `C:\Python27\Lib\site-
packages\win32\src`, and change code:
self.currentRound = int(config.read_config_co(r'src\restore.ini', 'Record')['currentRound'])
config.write_config_update_co(self.currentRound-1, 'Record', 'currentRound', r'src\restore.ini')
Now, it's OK!
I want not move directory `src`, how do I do? Thanks!
Answer: if you use relative paths for file or directory names python will look for
them (or create them) in your current working directory (the $PWD variable in
bash; something similar on windows?).
if you want to have them relative to the current python file, you can use
(python 3.4)
from pathlib import Path
HERE = Path(__file__).parent.resolve()
RESTORE_INI = HERE / 'restore.ini'
or (python 2.7)
import os.path
HERE = os.path.abspath(os.path.dirname(__file__))
RESTORE_INI = os.path.join(HERE, 'restore.ini')
if your `restore.ini` file lives in the same directory as your python script.
then you can use that in
def setUp(self):
self.currentRound = int(config.read_config_co(RESTORE_INI,
'Record')['currentRound'])
|
How do I upload full directory on FTP in python?
Question: Ok, so I have to upload a directory, with subdirectories and files inside, on
a FTP server. But I can't seem to get it right. I want to upload the directory
as it is, with it's subdirectories and files where they were.
ftp = FTP()
ftp.connect('host',port)
ftp.login('user','pass')
filenameCV = "directorypath"
def placeFiles():
for root,dirnames,filenames in os.walk(filenameCV):
for files in filenames:
print(files)
ftp.storbinary('STOR ' + files, open(files,'rb'))
ftp.quit()
placeFiles()
Answer: There are multiple problems with your code: First, the `filenames` array will
only contain the actual filenames, not the entire path, so you need to join it
with `fullpath = os.path.join(root, files)` and then use `open(fullpath)`.
Secondly, you quit the FTP connection inside the loop, move that `ftp.quit()`
down on the level of the `placeFiles()` function.
To recursively upload your directory, you have to walk through your root
directories and at the same time through your remote directory, uploading
files on the go.
Full example code:
import os.path, os
from ftplib import FTP, error_perm
host = 'localhost'
port = 21
ftp = FTP()
ftp.connect(host,port)
ftp.login('user','pass')
filenameCV = "directorypath"
def placeFiles(ftp, path):
for name in os.listdir(path):
localpath = os.path.join(path, name)
if os.path.isfile(localpath):
print("STOR", name, localpath)
ftp.storbinary('STOR ' + name, open(localpath,'rb'))
elif os.path.isdir(localpath):
print("MKD", name)
try:
ftp.mkd(name)
# ignore "directory already exists"
except error_perm as e:
if not e.args[0].startswith('550'):
raise
print("CWD", name)
ftp.cwd(name)
placeFiles(ftp, localpath)
print("CWD", "..")
ftp.cwd("..")
placeFiles(ftp, filenameCV)
ftp.quit()
|
problems with python nosetests
Question: I have problems with python nosetests. When I try to run the command, I get an
import error. I checked that the module is correctly installed on my machine.
In fact, if I run the interpreter from the directory where I run nosetests, I
am able to import the module. I checked that the problems are to import not
only that module, but different ones. Where could the fix be?
Here is a possible traceback after I run nosetests:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
addr.filename, addr.module)
File "/Library/Python/2.7/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/Library/Python/2.7/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/Users/user-me/Desktop/bla/tests/blatest1", line 1, in <module>
import a_module as mo
ImportError: No module named a_module
but if I open the python interpreter, I am able to import a_module.
Here is my directory structure:
ROOT
└── package
├── __init__.py
├── package1
└── tests
├── tests1
│ └── package1 -> ../../package1
└── tests2
Answer: Your problem has nothing to do with nose itself. nose doesn't perform any
magic additional to the Python interpreter when looking up modules and
packages.
So if we assume a directory structure like this
ROOT
`-- package
|-- __init__.py
`-- tests
`-- __init__.py
and try to do `python -c import package` \- when does that work, and when
fail?
It's simple. It fails anywhere other than if you invoke the command from
within `ROOT`. Nowhere else `package` is known.
The reason is that Python keeps a list of paths (sys.path) which mark roots
for packages and modules. A statement `import package` will be taken, and
iterating through all entries in `sys.path` will be searched for either a
`package.py`, a `package`-dir with an `__init__.py` in it, or some other cases
(C-extensions, new style namespace packages)
So where does `ROOT` get into that list of paths? Simple: the Python
interpreter will always add the current working directory to the list of
paths.
To sum it up: just call nose from within `ROOT`.
There are additional ways to add a path to the `sys.path`, e.g. by using
virtualenvs. Then you can import `package` from everywhere, given you use the
venv interpreter.
|
delegate SIGINT signal to child process and then cleanup and terminate the parent
Question: I have a main python(testmain.py) script that executes another python
script(test.py) using subprocess.Popen command. When I press Ctrl-C , I want
the child to exit with exit code 2 and then the parent to display that exit
code and then terminate .
I have signal handlers in both parent and child scripts.
testmain.py
def signal_handler(signal, frame):
print "outer signal handler"
exit(2)
signal.signal(signal.SIGINT, signal_handler)
def execute()
proc=subprocess.Popen("python test.py",shell=True)
streamdata=proc.communicate()[0]
rc=proc.returncode
print "return code:",rc
execute()
test.py
def signal_handler(signal, frame):
print "exiting: inner function"
exit(2)
signal.signal(signal.SIGINT, signal_handler)
I checked [Delegate signal handling to a child process in
python](http://stackoverflow.com/questions/24936107/delegate-signal-handling-
to-a-child-process-in-python) that is kind of similar to my question but in
that case, the parent is continuing it's execution, which I don't want.
I want to: 1.exit test.py with exit(2) 2.print that exit code in testmain.py
3.exit test.py with exit(2)
could someone please provide suggestions to do this? Thanks.
UPDATE : Handling the signal only in the child (test.py) and checking the
return code in parent(testmain.py) will do what I want .
if rc==2:
print "child was terminated"
exit(2)
but I was wondering if there is a clean way to do this using signal handling.
Answer: Your child process shouldn't care what the parent does i.e., if you want the
child to exit with specific status on Ctrl+C then just do that:
import sys
try:
main()
except KeyboardInterrupt: # use default SIGINT handler
sys.exit(2)
Or you could define the signal handler explicitly:
import os
import signal
def signal_handler(signal, frame):
os.write(1, b"outer signal handler\n")
os._exit(2)
signal.signal(signal.SIGINT, signal_handler)
main()
There might be a difference in behavior if there are `atexit` handlers and/or
multiple threads.
Unrelated: depending on what your `main()` function does, there could be a
significant delay before a signal is handled in Python. Some blocking methods
on Python 2 may ignore the signal completely: use Python 3 or apply a custom
workaround for a specific case e.g., using a timeout parameter for some calls.
* * *
You could handle `SIGINT` in a similar way in the parent:
for cmd in commands:
process = Popen(cmd)
try:
process.wait()
except KeyboardInterrupt:
# child process may still be alive here
for _ in range(5): # wait a while
if process.poll() is not None:
break # the process is dead
time.sleep(.1)
else: # no break, kill the process explicitly
try:
process.kill()
except OSError:
pass
sys.exit("Child exited with %d" % process.wait())
Python 2 doesn't restore signals for child processes e.g., if you `SIG_IGN`
the `SIGINT` signal in the parent, [you could reset the necessary hanlders
explicitly using `preexec_fn`
parameter](http://stackoverflow.com/a/22083141/4279).
|
Unit Testing for user input and expected output in Python
Question: I'm fairly new to unit test in Python, but have done a few so I understand the
basics of it. One problem I'm having is being able to mock input and then test
for the STDOUT based on that mocked input. I tried the solution in this post:
[python mocking raw input in
unittests](http://stackoverflow.com/questions/21046717/python-mocking-raw-
input-in-unittests) but didn't find any success with the given method. My test
seems like it's getting hung up when asking for the input. I want to be able
to mock the input for the `Run` module and then be able to test for the STDOUT
which can be either `True/False` Here is my `Run` code
#imports
import random
def main():
#variables
dolphins = random.randrange(1,11)
guess = int(input("This is a prompt"))
print(guess == dolphins)
Really simple here. Here is my Testsuite
import unittest
from unittest.mock import patch
from Run import *
class GetInputTest(unittest.TestCase):
@patch('builtins.input', return_value=1)
def test_answer_false(self, input):
self.assertEqual(main(), 'False')
if __name__ == "__main__":
unittest.main()
So here I am feeding the input a value of `1` and then call the `main()`
during my assertion and expect a value of `False` but it doesn't even get that
far, the program just continuously runs, I think because it's waiting for an
`input` and I may not be mocking it correctly. I also tried feeding
`builtins.input` into the `@patch` parameter and I get the same result.
There's no error messages or tracebacks. Hopefully someone with a little more
experience can tell me what I am doing wrong. Thank you all in advance for
helping me out.
Answer: You can make your main as a function that takes arguments instead.
def main(args):
...do stuff
if __name__ == '__main__':
args = input('Get input')
main(args)
Then just unittest it as a normal function.
class TestMain(unittest.TestCase):
def testmain(self):
self.assertTrue(main(5), 'foo')
If you still want to have the input within your main, then you need to mock
patch `input` not `main`.
|
Why do I get an error for incorrect number of arguments?
Question: I have:
import datetime
class Animal(object):
def __init__(self, dob, carnivore):
self.__dob = dob
self.__carnivore = carnivore
@property
def dob(self):
return self.__dob
@dob.setter
def dob(self, dob):
self.__dob = dob
@property
def carnivore(self):
return self.__carnivore
@carnivore.setter
def carnivore(self, carnivore):
self.__carnivore = carnivore
def __str__(self):
return "DOB: " + str(self.__dob) + "\nCarnivore: " + str(self.__carnivore)
My second class:
import Species.Animal as Animal
import datetime as date
class Amphibian(Animal):
def __init__(self, dob=date.datetime.now(), carnivore=False, *characteristics):
super(Animal, self).__init__(dob, carnivore)
self.__characteristics = []
for characteristic in characteristics:
self.__characteristics.append(characteristic)
@property
def characteristics(self):
return self.__characteristics
@characteristics.setter
def characteristics(self, characteristic):
self.__characteristics.append(characteristic)
def __str__(self):
characteristics = ""
for characteristic in self.__characteristics:
characteristics += str(characteristic)
return characteristics
Using:
amphibian = Amphibian(date.date(1979, 1, 12), True, "BackBone", "Cold Blooded")
print(amphibian)
I get the error:
> Traceback (most recent call last): File
> "C:/Users/Daniel/PycharmProjects/ObjectOrientedSpecies/Species/Amphibian.py",
> line 7, in class Amphibian(Animal): TypeError: module.__init__() takes at
> most 2 arguments (3 given)
I am new to Python so I'm not sure what good OO Practices are.
Answer: There are two issues I can see. Firstly you should call `super` on the class
name of the class you are calling `super` in (that is a bit of a mouthful) so
that line should be `super(Amphibian, self).__init__(dob, carnivore)` and
_not_ `super(Animal, self).__init__(dob, carnivore)`. Python will find the
baseclass `Animal` itself.
However the main problem is that the class `Animal` is (almost certainly) in a
file called "Animal.py". Python makes a module called `Animal` automagically
when it sees a file called "Animal.py" (and does something similar for all
other ".py" names. So your class `Animal` is, in fact inside a module called
`Animal`.
Therefore when you do `import Species.Animal as Animal` you are importing the
_module_ not the class inside it. So when you do `class Amphibian(Animal):`
your Amphibians are inheriting from the class `module` not from the class
`Animal`. You need to change your import to the following to get the class
`Animal` instead: `from Species.Animal import Animal`.
In terms of your style I don't really see the point of having lots of
decorated getters and setters if there is nothing going on inside them except
simple getting and setting. Just get rid of the underscores in front of the
atribute names and use them directly. You only need to use the getters and
setters if something else has to happen to do the getting and setting.
|
How to I send keystroke to Linux process in Python by PID?
Question: One simple question: I have Linux process ID, which is 3789. How can I send
'ENTER' to this process by using Python?
Answer: You are able to do such thing but with proc name using Python
[subprocess](https://docs.python.org/2/library/subprocess.html#subprocess.Popen)
but not with PID.
from subprocess import Popen, PIPE
p = Popen(['proc_name', filePath], stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
p.stdin.print('\n') # sends Enter into process
|
Why can Python not recognize spark when I import?
Question: Python spits out an error when I try to import spark:
import pyspark.context
And the error is
Traceback (most recent call last):
File "<pyshell#N>", line 1, in <module>
import pyspark.context
ImportError: No module named pyspark.context
I have added the following to my `.bashrc` file, and I re-ran the terminal,
too:
export SPARK_HOME="/Users/<username>/Downloads/spark-1.4.0"
export PYTHONPATH=$SPARK_HOME/python/:$PYTHONPATH
The path to `SPARK_HOME` is the path preceding `/bin/pyspark`, and it contains
the folder `python`, as it should.
My `PYTHONPATH` seems correct however, since I can import `numpy` and such.
What could be the problem?
Answer: Try load pyspark programmatically:
import sys
try:
sys.path.append("/Users/<username>/Downloads/spark-1.4.0/python/")
from pyspark import context
print ("Successfully imported Spark Modules")
except ImportError as e:
print ("Can not import Spark Modules", e)
|
Unknown error with running the nosetests from Learning Python the Hard Way Ex46
Question: I am working on [ex46](http://learnpythonthehardway.org/book/ex46.html) from
Learning Python the Hard way.
I first created tests/NAME_tests.py as the following:
from nose.tools import *
import NAME
def setup():
print "SETUP!"
def teardown():
print "TEAR DOWN!"
def test_basic():
print "I RAN!"
And then I ran `~/projects/skeleton $ nosetests`
However, I am getting the following error and I have no idea why there is a
missing parenthesis.
print "SETUP!"
^
SyntaxError: Missing parentheses in call to 'print'
[](http://i.stack.imgur.com/ybkYY.png)
Answer: You are using _Python 3.4_ as can be seen from the paths in the screenshot.
In Python 3.x , `print` is a function, not a statement. You should use it as a
function. Example -
print("SETUP!")
Similarly for all prints .
The Example in [ex46](http://learnpythonthehardway.org/book/ex46.html) is most
probably written for Python 2 (In which `print` was a statement) .
|
unable to run scrapy in ec2
Question: I'm trying to run a code on an ec2 server. It is a python scrapy project which
is executed fine on my own pc. when trying to run it in the ec2 i get this:
Traceback (most recent call last):
File "/usr/local/bin/scrapy", line 4, in <module>
execute()
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 122, in execute
cmds = _get_commands_dict(settings, inproject)
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 46, in _get_commands_dict
cmds = _get_commands_from_module('scrapy.commands', inproject)
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 29, in _get_commands_from_module
for cmd in _iter_command_classes(module):
File "/usr/local/lib/python2.7/site-packages/scrapy/cmdline.py", line 20, in _iter_command_classes
for module in walk_modules(module_name):
File "/usr/local/lib/python2.7/site-packages/scrapy/utils/misc.py", line 68, in walk_modules
submod = import_module(fullpath)
File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/usr/local/lib/python2.7/site-packages/scrapy/commands/bench.py", line 3, in <module>
from scrapy.tests.mockserver import MockServer
File "/usr/local/lib/python2.7/site-packages/scrapy/tests/mockserver.py", line 6, in <module>
from twisted.internet import reactor, defer, ssl
File "/usr/local/lib/python2.7/site-packages/twisted/internet/ssl.py", line 59, in <module>
from OpenSSL import SSL
File "/usr/local/lib/python2.7/site-packages/OpenSSL/__init__.py", line 8, in <module>
from OpenSSL import rand, crypto, SSL
File "/usr/local/lib/python2.7/site-packages/OpenSSL/rand.py", line 11, in <module>
from OpenSSL._util import (
File "/usr/local/lib/python2.7/site-packages/OpenSSL/_util.py", line 4, in <module>
binding = Binding()
File "/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 87, in __init__
self._ensure_ffi_initialized()
File "/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 106, in _ensure_ffi_initialized
libraries=libraries,
File "/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/utils.py", line 39, in build_ffi
ffi = cffi.FFI()
File "/usr/local/lib/python2.7/site-packages/cffi/api.py", line 56, in __init__
**import _cffi_backend as backend
ImportError: libffi.so.5: cannot open shared object file: No such file or directory**
I've tried to update && reinstall all the mentioned libraries.
it always says it is most updated version.
this is my linux distro and default python is 2.7:
# cat /etc/*-release
NAME="Amazon Linux AMI"
VERSION="2015.03"
ID="amzn"
ID_LIKE="rhel fedora"
VERSION_ID="2015.03"
PRETTY_NAME="Amazon Linux AMI 2015.03"
ANSI_COLOR="0;33"
CPE_NAME="cpe:/o:amazon:linux:2015.03:ga"
HOME_URL="http://aws.amazon.com/amazon-linux-ami/"
Amazon Linux AMI release 2015.03
UPDATE: it looks like some sort of problem in scrapy dependencies. trying
pip install scrapy
gave me the following error:
creating /usr/lib/python2.6/dist-packages/cssselect
error: could not create '/usr/lib/python2.6/dist-packages/cssselect': Permission denied
----------------------------------------
Command "/usr/bin/python2.6 -c "import setuptools,
tokenize;__file__='/tmp/pip-build- aoghBl/cssselect/setup.py'
;exec(compile(getattr(tokenize, 'open', open)
(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
install --record /tmp/pip-1Qpx2a-record/install-record.txt
--single-version-externally-managed --compile"
failed with error code 1 in /tmp/pip-build-aoghBl/cssselect
Answer: Your updated question is a permissions error. you likely need to run
sudo pip install cssselect
May need to do that for other dependancies. It's strange though that it's
trying to install under python2.6...
Edit: Given that it's trying to run under 2.6, something is wrong with your
instance. I'd suggest terminating and recreating the instance. The following
commands are what I ran to get scrapy dependancies and my project up and
running
sudo su
yum groupinstall 'Development Tools'
yum install -y libffi-devel libxslt-devel libxml2-devel openssl-devel python-devel mysql-devel
|
PIL im.getdata file format
Question: I'm new for Python, so sorry for stupid question. When I call for
list(im.getdata()) the result looks like a list with triple-tuple inside.
Simple list commands such as sum() doesn't want to work, claiming:
Traceback (most recent call last):
File "C:\Users\Poos\Desktop\G\SS.py", line 8, in <module>
y = sum(x)
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
What should I do to operate with this data as with a "normal" list? Thanks and
sorry for English inaccuracies
Answer: The list returned is the RGB value for each pixel, so each element _should_ be
a tuple with three elements. I don't know what you want to accomplish by
summing the elements. If you want to determine the 'total red component', you
can use list comprehension:
red = sum([x[0] for x in list(im.getdata())])
Maybe we can help you better if you better describe what you want to achieve.
**Equivalence**
Edit after first comment: if you want to check if two images are _equal_ ,
then you can compare the data, or the images directly.
>>> a = [(1,2,3), (4,5,6)]
>>> b = [(1,2,3), (4,5,6)]
>>> a == b
True
>>>> from PIL import Image
>>> a = Image.new("RGB", (250,250), "red")
>>> b = Image.new("RGB", (250,250), "red")
>>> a == b
True
>>> b.putpixel((100,100), (100,100,100))
>>> a == b
False
If you don't want to check for another kind of equivalence, you must specify
more in detail what you mean with equivalent.
|
Eurostat SDMX dataflow description python
Question: Using python I want to collect a list of all possible dataflows from Eurostat.
I have the following code;
from pandasdmx import Request as rq
estat=rq('ESTAT')
cat_rsp=estat.get(resource_type='dataflow')
cat_msg=cat_rsp.msg
print [i.encode('utf-8') for i in cat_msg.dataflows]
this gives me a list of all possible resource_id's but I want also the
descriptors. Is this possible?
Thanks
Answer: Dataflow instances have a `description` attribute if that is what you're
looking for.
print [i.description.en for i in cat_msg.dataflows]
Since Version 0.4 the preferred method is:
df = cat_rsp.write(columns=['name', 'description']).dataflow
This Returns a Pandas DataFrame that should contain descriptions on Dataflow
instances.
Note that since version 0.4 the 'dataflows' Attribute of msg is deprecated in
favor of 'dataflow'.
Leo
|
stdin reading blocking when running sbt with python subprocess.Popen()
Question: I'm launching sbt via Popen(), and my python process stdin reading is not
working. Here is an example: On the first line I'm launching Popen, on the
second line I'm trying to browse throught the history with an arrow key. This
does not work for some time, printing ^[[A.
$ python
Python 2.7.10 (default, Jul 13 2015, 12:05:58)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess; f = open("/dev/null", "rw"); subprocess.Popen(["sbt"], stdout=f, stderr=f, stdin=f)
<subprocess.Popen object at 0x10fc03950>
>>> ^[[A^[[A^[[A^[[A^[[A^[[A^[[A^[[A^[[Aimport subprocess; f = open("/dev/null", "rw"); subprocess.Popen(["sbt"], stdout=f, stderr=f, stdin=f)
This seems to only happen with sbt. Any idea why and how to bypass this
behavior ?
Thanks
Answer: My guess is that `sbt` is misbehaving when there is no pseudo-tty to interact
with the user (probably because of `jline`).
Hence, let's use a python module to run the commands in a pseudo-tty. Install
`pexpect` via pip (`pip3 install pexpect` for Python 3.x).
Then, run the following:
import pexpect, sys
f = open("sbt.log", "w+")
# Use `spawnu` for Python3, `spawn` otherwise
sbt = pexpect.spawnu("sbt -Dsbt.log.noformat=true \"version\" \"another-command\"", logfile=f)
# Do whatever is needed while sbt is running
# Force the process to expect EOF and file to be written
sbt.expect(pexpect.EOF)
Tested in Python 3.4.3 (Gentoo Linux) and works.
|
wx script can't see numpy, but it's installed
Question: I had a wx script working on winxp (at work). it was upgraded to win7_64. I
installed python2 and wxpython (both 32bit). now my script doesn't want to
run. it says "ImportError: NumPy not found.". so I installed numpy from
numpy.org, but it didnt change anything. I can import wx, I can import numpy,
but when I try to run my wx script, it says that numpy is not installed. I
removed and reinstalled everything but nothing changed. what to do?
Answer: Presumably your `numpy` is too "new" or your `wxPython` is too old. For
example the combination wxPython < 3.0 and numpy > 1.9 will not work for the
plot module (2.9.5 + numpy 1.8.0 and 3.0.2 + numpy 1.9.2 **do** actually
work).
Reason should be file `<site-packages.wx>/lib/plot.py` (2.9.5):
# Needs NumPy
try:
import numpy.oldnumeric as _Numeric
except:
msg= """
This module requires the NumPy module, which could not be
imported. It probably is not installed (it's not part of the
standard Python distribution). See the Numeric Python site
(http://numpy.scipy.org) for information on downloading source or
binaries."""
raise ImportError, "NumPy not found.\n" + msg
and as used in 3.0.2):
# Needs NumPy
try:
import numpy as np
except:
`numpy.oldnumeric` is no longer part of numpy 1.9.2, `wx.lib.plot` was
developed for ancient array libraries and you can clearly see its age.
|
Python requests module is very slow on specific machine
Question: I've experienced too slow execution of Python requests on some machines and
with specific user while other tools (for instance curl) are quite fast.
Strange thing is that if run the script as another user then it runs as
expected. If I run the script on my machine (both Windows or Linux) then it
runs as expected too. Problematic machines are Windows 2008 servers on
Hyper-V. I usually use POST request but both POST and GET are affected. For
the demonstration I've created simple script with GET request. All requests
take about 4.8s but it should take about 0.03s (virtual machines are not so
powerful).
[imports and logging configuration omitted]
log.info("Started ...")
start = time.time()
response1 = requests.get("http://10.50.30.216:8080/sps/api/version")
assert response1.status_code == codes.OK
log.info("Using requests: %.3fs" % (time.time() - start))
start = time.time()
conn = httplib.HTTPConnection("10.50.30.216:8080")
conn.request("GET", "/sps/api/version")
response2 = conn.getresponse()
assert response2.status == codes.OK
log.info("Using httplib: %.3fs" % (time.time() - start))
log.info("Finished ...")
Output when logged as problematic user (unfortunately I must use that user).
See that requests module waits 4.523s before opening a connection while
httplib module proceeds immediately.
2015-09-11 14:50:00,832 - INFO - myscript - Started ...
2015-09-11 14:50:05,355 - INFO - requests.packages.urllib3.connectionpool - Starting new HTTP connection (1): 10.50.30.216
2015-09-11 14:50:05,364 - DEBUG - requests.packages.urllib3.connectionpool - "GET /sps/api/version HTTP/1.1" 200 None
2015-09-11 14:50:05,365 - INFO - myscript - Using requests: 4.533s
2015-09-11 14:50:05,374 - INFO - myscript - Using httplib: 0.008s
2015-09-11 14:50:05,375 - INFO - myscript - Finished ...
Output when logged as another user. Note that both users have Administrator
privileges but the second user is only temporary and only on one machine so I
can't use solve this issue by switching users.
2015-09-11 14:57:45,789 - INFO - myscript - Started ...
2015-09-11 14:57:45,799 - INFO - requests.packages.urllib3.connectionpool - Starting new HTTP connection (1): 10.50.30.216
2015-09-11 14:57:45,806 - DEBUG - requests.packages.urllib3.connectionpool - "GET /sps/api/version HTTP/1.1" 200 None
2015-09-11 14:57:45,809 - INFO - myscript - Using requests: 0.021s
2015-09-11 14:57:45,815 - INFO - myscript - Using httplib: 0.004s
2015-09-11 14:57:45,815 - INFO - myscript - Finished ...
I've read [Python requests are slow
#1](http://stackoverflow.com/questions/15780679/python-requests-is-slow) and
[Python requests are slower thann
curl](http://stackoverflow.com/questions/18996177/python-requests-module-get-
post-various-rest-clients-requests-taking-longer-t) but it does not apply to
my problem.
Answer: There could be many things slowing the request down. Anything from DNS lookup,
throttling etc.
Try getting some more information by turning requests debug logging on
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
|
Matplotlib Basemap Plotting Lat/Lons
Question: I cannot for the life of me figure out how to animate points (earthquake
epicenters) on a Matplotlib basemap plot, using the animation function. I have
tried implementing
[this](http://stackoverflow.com/questions/21207513/matplotlib-basemap-
animation) example code into my script, but all my points plot at once. It may
have something to do with my function and the for loop within the function.
Any thoughts?
Here is my code:
#!/usr/local/bin/python
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig = plt.figure()
#Build the basemap
antmap = Basemap(projection='spstere', boundinglat=30, lon_0=-60, resolution='f')
antmap.drawcoastlines(color='black', linewidth=0.15)
antmap.bluemarble()
eq_data = open('eq_data')
lats, lons = [], []
mag = []
x,y = antmap(0,0)
point = antmap.plot(x,y,'ro', markersize=5)[0]
def init():
point.set_data([],[])
return point,
# Begin Animation
def animate(i):
for i, line in enumerate(eq_data.readlines()):
lats.append(float(line.split(',')[0]))
lons.append(float(line.split(',')[1]))
mag.append(float(line.split(',')[2]))
x,y = antmap(lons, lats)
point.set_data(x, y)
return point,
# antmap.plot(x,y, 'ro', markersize=8)
ani = animation.FuncAnimation(fig, animate, init_func=init, interval=500, blit=False)
plt.show()
How would I animate these points? I haven't been able to find anything else
online thus far that has been able to animate these earthquake epicenters.
Thanks.
**UPDATED AND CORRECTED SCRIPT**
#!/usr/local/bin/python
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
# Create the Figure
fig = plt.figure()
#Build the basemap
antmap = Basemap(projection='spstere', boundinglat=30, lon_0=-60, resolution='l')
antmap.drawcoastlines(color='black', linewidth=0.15)
#antmap.bluemarble()
eq_data = open('eq_data')
lats, lons = [], []
mag = []
x,y = antmap(lons,lats)
for i, line in enumerate(eq_data.readlines()):
lats.append(float(line.split(',')[0]))
lons.append(float(line.split(',')[1]))
mag.append(float(line.split(',')[2]))
eq_data.close()
antmap.plot(x,y,'ro', markersize=5)
# Begin Animation
def animate(i):
x,y = antmap(lons[i], lats[i])
antmap.plot(x,y,'ro', markersize=8)
animation = FuncAnimation(fig, animate, interval=100, blit=False)
plt.show()
Answer: I think you want to build your `lats` and `lons` lists outside of the
`animate` function, then just plot one point at a time inside the function.
`animate` is called sequentially with an increasing `i`, so we can use that to
index the `lons` and `lats` lists.
(Note, I haven't tested this, but I think it should work)
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig = plt.figure()
#Build the basemap
antmap = Basemap(projection='spstere', boundinglat=30, lon_0=-60, resolution='f')
antmap.drawcoastlines(color='black', linewidth=0.15)
antmap.bluemarble()
eq_data = open('eq_data')
lats, lons = [], []
mag = []
x,y = antmap(0,0)
point = antmap.plot(x,y,'ro', markersize=5)[0]
# Read the data and build the lists of coordinates here
for i, line in enumerate(eq_data.readlines()):
lats.append(float(line.split(',')[0]))
lons.append(float(line.split(',')[1]))
mag.append(float(line.split(',')[2]))
eq_data.close()
def init():
point.set_data([],[])
return point,
# Begin Animation
def animate(i):
x,y = antmap(lons[i], lats[i])
point.set_data(x, y)
return point,
ani = animation.FuncAnimation(fig, animate, init_func=init, interval=500, blit=False)
plt.show()
|
Finding server in LAN
Question: How to find, in python, server without having it's IP in LAN?
I assume that port will be configured in file so its doesn't have to find
port.
I tried to search on google but I couldn't find anything useful or that could
help me with it.
The server IP will be changing because it will not run constantly on the same
computer.
So basically I got app with server that is on random computer in network, and
I want to find its IP from another computer.
I would be really thankful for either explanation how to do it or link that
could help me to do it.
Answer: Not certain if this is what you want to do, I think you want to find the IP of
a server by running some python execution on the server?
You could try :
from subprocess import call
call (["ipconfig"])
This will dump the IP config and you can parse out the IP address. This
assumes a windows server. You would have to modify the call for your OS.
* * *
Updated :
Check this out : [TCP
Communications](http://wiki.python.org/moin/TcpCommunication) or [UDP
Communications](http://wiki.python.org/moin/UdpCommunication) ... it looks
like what you are looking for. You will still have the mess of determining the
available addresses on the network (arp -a), and testing each one - this would
be your client side app. Your server side app, when it receives the right
query on the TCP or UDP port, would then determine it's address (ipconfig) and
return the value.
|
Terminate sudo python script when the terminal closes
Question: How can I tell if the terminal running my python script was closed? I want to
safely end my python script if the user closes the terminal. I can catch
SIGHUP with a handler, but not when the script is run as sudo. When I start
the script with sudo and close the terminal, the python script keeps running.
Example script:
import signal
import time
import sys
def handler(signum, frame):
fd = open ("tmp.txt", "a")
fd.write(str(signum) + " handled\n")
fd.close()
sys.exit(0)
signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
time.sleep(50)
Sometimes the script will execute the handler when run as sudo, but more often
it doesn't. The script always writes to the file when ran without sudo. I am
running it on a Raspberry Pi. I see the same thing in a LXTerminal and a
gnome-terminal. This example script will end after 50 seconds, but my lengthy
code runs in an infinite loop
The ultimate goal is to have a .desktop launcher on a Raspberry Pi to do
bluetooth scanning and find devices. The bluetooth scanning requires sudo
because it use 4.0 BLE. I'm not sure why bluez requires sudo but it does. When
type sudo on the pi, it never asks for a password which is fine with me. The
problem is that after closing the terminal, the scan process is still running.
The scanning is done by a python script that runs in a terminal.
Answer: sudo is designed for the SIGHUP semantics you get when it's a child of some
other process on the tty. In that case, all processes get their own SIGHUP
from the kernel when the parent exits.
`xterm -e sudo cmd` runs sudo directly on the pseudo-terminal. This produces
different SIGHUP semantics than sudo is expecting. Only sudo receives a SIGHUP
from the kernel, and doesn't relay it because it's expecting that it gets a
SIGHUP from the kernel only when its child process also got its own (because
of something sudo's parent (e.g. bash) does).
I [reported the issue upstream](http://bugzilla.sudo.ws/show_bug.cgi?id=719),
and **it's now marked as fixed in sudo 1.8.15 and onwards**.
## Workaround:
xterm -e 'sudo ./sig-counter; true'
# or for uses that don't implicitly use a shell:
xterm -e sh -c 'sudo some-cmd; true'
If your `-c` argument is a single command, bash optimizes by execing it.
Tacking another command (the trivial `true` in this case), gets bash to stick
around and run sudo as a child. I tested, and with this method, sig-counter
gets one SIGHUP from the kernel when you close xterm. (It should be the same
for any other terminal emulator.)
I've tested this, and it works with bash and dash. Source included for a
handy-dandy signal-receiving-without-exiting program which you can strace to
see all the signals it receives.
* * *
Some parts of the rest of this answer may be slightly out of sync. I went
through a few theories and testing methods before figuring out the sudo as
controlling process vs. sudo as child of a shell difference.
* * *
[POSIX
says](http://pubs.opengroup.org/onlinepubs/9699919799/functions/close.html)
that `close()` on the master end of a pseudo-terminal causes this: "a SIGHUP
signal shall be sent to the controlling process, if any, for which the slave
side of the pseudo-terminal is the controlling terminal."
The POSIX wording for `close()` implies there can be only one processing
process that has the pty as its controlling terminal.
When bash is the controlling process for the slave side of a pty, it does
something that causes all other processes to receive a SIGHUP. This is the
semantics sudo is expecting.
`ssh localhost`, then abort the connection with `~.` or kill your ssh client.
$ ssh localhost
ssh$ sudo ~/.../sig-counter # without exec
# on session close: gets a SIGHUP and a SIGCONT from the kernel
$ ssh localhost
ssh$ exec sudo ~/src/experiments-sys/sig-counter
# on session close: gets only a SIGCONT SI_USER relayed from sudo
$ ssh -t localhost sudo ~/src/experiments-sys/sig-counter
# on session close: gets only a SIGCONT SI_USER relayed from sudo
$ xterm -e sudo ./sig-counter
# on close: gets only a SIGCONT SI_USER relayed from sudo
* * *
Testing this was tricky, because `xterm` also sends a SIGHUP on its own,
before exiting and closing the pty. Other terminal emulators (gnome-terminal,
konsole) may or may not do this. I had to write a signal-testing program
myself to not just die after the first SIGHUP.
Unless xterm is running as root, it can't send signals to sudo, so sudo only
gets the signals from the kernel. (Because it is the controlling process for
the tty, and the process running under sudo isn't.)
The `sudo` man page says:
> Unless the command is being run in a new pty, the SIGHUP, SIGINT and SIGQUIT
> signals are not relayed unless they are sent by a user process, not the
> kernel. Otherwise, the command would receive SIGINT twice every time the
> user entered control-C.
It looks to me like sudo's double-signal avoidance logic for SIGHUP was
designed for running as a child of an interactive shell. When there's no
interactive shell involved (after `exec sudo` from an interactive shell, or
when there was no shell involved in the first place), only the parent process
(sudo) gets a SIGHUP.
sudo's behaviour is good for SIGINT and SIGQUIT, even in an xterm with no
shell involved: after pressing ^C or ^\ in the xterm, `sig-counter` receives
exactly one SIGINT or SIGQUIT. `sudo` receives one and doesn't relay it.
`si_code=SI_KERNEL` in both processes.
* * *
Tested on Ubuntu 15.04, `sudo --version`: 1.8.9p5. `xterm -v`: XTerm(312).
###### No sudo
$ pkill sig-counter; xterm -e ./sig-counter &
$ strace -p $(pidof sig-counter)
Process 19446 attached
quit xterm (ctrl-left click -> quit)
rt_sigtimedwait(~[TERM RTMIN RT_1], {si_signo=SIGHUP, si_code=SI_USER, si_pid=19444, si_uid=1000}, NULL, 8) = 1 # from xterm
rt_sigtimedwait(~[TERM RTMIN RT_1], {si_signo=SIGHUP, si_code=SI_KERNEL}, NULL, 8) = 1 # from the kernel
rt_sigtimedwait(~[TERM RTMIN RT_1], {si_signo=SIGCONT, si_code=SI_KERNEL}, NULL, 8) = 18 # from the kernel
sig-counter is still running, because it only exits on SIGTERM
#### with sudo, attaching to sudo and sig-counter after the fact
# Then send SIGUSR1 to sudo
# Then quit xterm
$ sudo pkill sig-counter; xterm -e sudo ./sig-counter &
$ sudo strace -p 20398 # sudo's pid
restart_syscall(<... resuming interrupted call ...>) = ?
ERESTART_RESTARTBLOCK (Interrupted by signal)
--- SIGUSR1 {si_signo=SIGUSR1, si_code=SI_USER, si_pid=20540, si_uid=0} ---
write(7, "\n", 1) = 1 # FD 7 is the write end of a pipe. sudo's FD 6 is the other end. Some kind of deadlock-avoidance?
rt_sigreturn() = -1 EINTR (Interrupted system call)
poll([{fd=6, events=POLLIN}], 1, 4294967295) = 1 ([{fd=6, revents=POLLIN}])
read(6, "\n", 1) = 1
kill(20399, SIGUSR1) = 0 ##### Passes it on to child
read(6, 0x7fff67d916ab, 1) = -1 EAGAIN (Resource temporarily unavailable)
poll([{fd=6, events=POLLIN}], 1, 4294967295
####### close xterm
--- SIGHUP {si_signo=SIGHUP, si_code=SI_KERNEL} ---
rt_sigreturn() = -1 EINTR (Interrupted system call)
--- SIGCONT {si_signo=SIGCONT, si_code=SI_KERNEL} --- ### sudo gets both SIGHUP and SIGCONT
write(7, "\22", 1) = 1
rt_sigreturn() = -1 EINTR (Interrupted system call)
poll([{fd=6, events=POLLIN}], 1, 4294967295) = 1 ([{fd=6, revents=POLLIN}])
read(6, "\22", 1) = 1
kill(20399, SIGCONT) = 0 ## but only passes on SIGCONT
read(6, 0x7fff67d916ab, 1) = -1 EAGAIN (Resource temporarily unavailable)
poll([{fd=6, events=POLLIN}], 1, 4294967295
## keeps running after xterm closes
$ sudo strace -p $(pidof sig-counter) # in another window
rt_sigtimedwait(~[RTMIN RT_1], {si_signo=SIGUSR1, si_code=SI_USER, si_pid=20398, si_uid=0}, NULL, 8) = 10
rt_sigtimedwait(~[RTMIN RT_1], {si_signo=SIGCONT, si_code=SI_USER, si_pid=20398, si_uid=0}, NULL, 8) = 18
## keeps running after xterm closes
The command running under `sudo` only sees a SIGCONT when the xterm closes.
Note that clicking the window-manager's close button on xterm's titlebar just
makes xterm send a SIGHUP manually. Often this will cause the process inside
xterm to close, in which case xterm exits after that. Again, this is just
xterm's behaviour.
* * *
This is what `bash` does when it gets SIGHUP, producing the behaviour `sudo`
expects:
Process 26121 attached
wait4(-1, 0x7ffc9b8c78c0, WSTOPPED|WCONTINUED, NULL) = ? ERESTARTSYS (To be restarted if SA_RESTART is set)
--- SIGHUP {si_signo=SIGHUP, si_code=SI_KERNEL} ---
--- SIGCONT {si_signo=SIGCONT, si_code=SI_KERNEL} ---
... write .bash history ...
kill(4294941137, SIGHUP) = -1 EPERM (Operation not permitted) # This is kill(-26159), which signals all processes in that process group
rt_sigprocmask(SIG_BLOCK, [CHLD TSTP TTIN TTOU], [CHLD], 8) = 0
ioctl(255, SNDRV_TIMER_IOCTL_SELECT or TIOCSPGRP, [26121]) = -1 ENOTTY (Inappropriate ioctl for device) # tcsetpgrp()
rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
setpgid(0, 26121) = -1 EPERM (Operation not permitted)
rt_sigaction(SIGHUP, {SIG_DFL, [], SA_RESTORER, 0x7f3b25ebf2f0}, {0x45dec0, [HUP INT ILL TRAP ABRT BUS FPE USR1 SEGV USR2 PIPE ALRM TERM XCPU XFSZ VTALRM SYS], SA_RESTORER, 0x7f3b25ebf2f0}, 8) = 0
kill(26121, SIGHUP) = 0 ## exit in a way that lets bash's parent see that SIGHUP killed it.
--- SIGHUP {si_signo=SIGHUP, si_code=SI_USER, si_pid=26121, si_uid=1000} ---
+++ killed by SIGHUP +++
I'm not sure which part of this gets the job done. Probably the actual exiting
is the trick, or something it did before launching the command, since `kill`
and `tcsetpgrp()` both failed.
* * *
My first attempt at trying it myself was:
xterm -e sudo strace -o /dev/pts/11 sleep 60
(where pts/11 is another terminal.) `sleep` exits after the first SIGHUP, so
testing without sudo just shows the SIGHUP sent manually by xterm.
sig-counter.c:
// sig-counter.c.
// http://stackoverflow.com/questions/32511170/terminate-sudo-python-script-when-the-terminal-closes
// gcc -Wall -Os -std=gnu11 sig-counter.c -o sig-counter
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
int sigcounts[64];
static const int sigcount_size = sizeof(sigcounts)/sizeof(sigcounts[0]);
void handler(int sig_num)
{
sig_num = min(sig_num, sigcount_size);
sigcounts[sig_num]++;
}
int main(void)
{
sigset_t sigset;
sigfillset(&sigset);
// sigdelset(&sigset, SIGTERM);
if (sigprocmask(SIG_BLOCK, &sigset, NULL))
perror("sigprocmask: ");
const struct timespec timeout = { .tv_sec = 60 };
int sig;
do {
// synchronously receive signals, instead of installing a handler
siginfo_t siginfo;
int ret = sigtimedwait(&sigset, &siginfo, &timeout);
if (-1 == ret) {
if (errno == EAGAIN) break; // exit after 60 secs with no signals
else continue;
}
sig = siginfo.si_signo;
// switch(siginfo.si_code) {
// case SI_USER: // printf some stuff about the signal... just use strace
handler(sig);
} while (sig != SIGTERM );
//sigaction(handler, ...);
//sleep(60);
for (int i=0; i<sigcount_size ; i++) {
if (sigcounts[i]) {
printf("counts[%d] = %d\n", i, sigcounts[i]);
}
}
}
My first attempt at this was perl, but installing a signal handler wasn't
stopping perl from exitting on SIGHUP after the signal handler returned. I saw
the message appear right before xterm closed.
cmd=perl\ -e\ \''use strict; use warnings; use sigtrap qw/handler signal_handler normal-signals/; sleep(60); sub signal_handler { print "Caught a signal $!"; }'\';
xterm -e "$cmd" &
Apparently perl signal handling is fairly complicated because perl has to
[defer them until it's not in the middle of something that doesn't do proper
locking](http://perldoc.perl.org/perlipc.html#Deferred-Signals-%28Safe-
Signals%29).
Unix syscalls in C is the "default" way to do systems programming, so that
takes out any possible confusion. strace is often a cheap way to avoid
actually writing logging / printing code for playing around with stuff. :P
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.