text
stringlengths 226
34.5k
|
---|
Customize operation/function on Theano
Question: I am new to the Theano library, which is used for deep learning on GPU device.
I have noticed that there are several build-in operations which can support
gpu computation (I guess they are specially written in a way to support GPU):
import theano.tensor as T
T.sum(), T.neq(), T.argmax(),T.grad()
1.What's the difference if I use python's build-in function sum() instead of
T.sum(). Will sum() still work but maybe slower?
2. Suppose sum() doesn't work for gpu computing, then if I need any operation/function that workable on gpu, I need to implement it in such a way. e.g. I want calculate sin(x) where x is a vector or matrix, and stored in GPU memory. Is there any hint to implement sin(x) that can operate on gpu device? (this might not be suitable or easy to answer)
3. I have trouble understanding T.grad(). How T.grad can do the symbolic calculation for any given smooth symbolic function? I am very curious about it.
Answer: In theano you have to use `T.sum(), T.neq(), T.argmax(),T.grad()` for symbolic
computation with theano variables like `T.matrix`. You can't use built in
`sum()` for example. If you use theano you have to follow theano's own methods
because theano uses a different form of computing to utilize the gpu's
architecture.
However if you want to use `sum()` you can do the computation with it, and
then create a `theano.shared` variable where you can store the results in,
this way you storing it in the gpu's memory at runtime.
Regarding T.grad() perhaps you should ask the theano developers. :) However I
think when theano is running, it can compute the function's gradient runtime,
using the actual variables utilizing the gpu's computing capacity. I hope this
can help.
**Glad to have been of help! Feel free to accept my answer if you feel it was
useful to you. :-)**
|
Passing arguments to a embedded python script in bash
Question: I'm having difficulties passing arguments to a embedded bash script.
#!/bin/bash/
function my_function() {
MYPARSER="$1" python - <<END
<<Some Python Code>>
class MyParser(OptionParser):
def format_epilog(self, formatter):
return self.epilog
parser=MyParser(version=VER, usage=USAGE, epilog=DESC)
parser.add_option("-s", "--Startdir", dest="StartDir",
metavar="StartDir"
)
parser.add_option("-r", "--report", dest="ReportDir",
metavar="ReportDir"
)
<<More Python Code>>
END
}
foo="-s /mnt/folder -r /storagefolder/"
my_function "$foo"
I've read [Steve's Blog: Embedding python in bash
scripts](http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-
scripts.html) which helped but I'm still unable to pass the argument. I've
tried both parser and myparser as environmental variables.
Is it as simple as defining $2 and passing them individually?
Thanks
Answer: You're overcomplicating this rather a lot. Why mess with a parser where
value="hello" python -c 'import os; print os.environ["value"]'
Or, for a longer script:
value="hello" python <<'EOF'
import os
print os.environ["value"]
EOF
* * *
If you need to set `sys.argv` for compatibility with existing code:
python - first second <<<'import sys; print sys.argv'
Thus:
args=( -s /mnt/folder -r /storagefolder/ )
python - "${args[@]}" <<'EOF'
import sys
print sys.argv # this is what an OptionParser will be looking at by default.
EOF
|
Post image retrieved from urlopen
Question: I would to send a file to the Telegram Bot
[API](https://core.telegram.org/bots/api#sendphoto) in order to post a
picture. I am using python on Google App Engine and I would like to download a
picture from a URL and send it in a Telegram message, without creating any
intermediate file on disk (which I believe isnt't even possible given the
platform).
I have successfully sent an image taken from disk, but no matter what I try, I
am not able to send a picture retrieved from a URL. Here is the working code:
import urllib2
import requests
photo = open('cat.jpg', 'r')
#photo = urllib2.urlopen('http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg')
resp = requests.post(BASE_URL + 'sendPhoto',
files={'photo' : photo},
data={'chat_id' : '95297807'},
)
If I get photo with urlopen it won't work. I tried using StringIO, but it
doesn't work either. Any ideas?
Answer:
import urllib2
from StringIO import StringIO
from PIL import Image
url='http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg'
photo=Image.open(StringIO(urllib2.urlopen(url).read()))
|
Ubuntu 14.04, gcc 4.8.4: gdb pretty printing doesn't work because of Python issue
Question: I'm getting this error when launching a program in gdb:
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Traceback (most recent call last):
File "/usr/share/gdb/auto-load/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.19-gdb.py", line 63, in <module>
from libstdcxx.v6.printers import register_libstdcxx_printers
ImportError: No module named 'libstdcxx'
Google turned up this bug report: <http://osdir.com/ml/debian-
gcc/2014-02/msg00061.html> This bug report list using the command `python
print sys.path` on the gdb prompt. However, when I try to use any python on
the gdb prompt, this happens:
(gdb) python print sys.path
File "<string>", line 1
print sys.path
^
SyntaxError: invalid syntax
Error while executing Python code.
(gdb) python print "Hello"
File "<string>", line 1
print "HellO"
^
SyntaxError: invalid syntax
Error while executing Python code.
I'm using Ubuntu 14.04 LTS, relevant version information:
$ gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
$ gdb --version
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
$ python --version
Python 2.7.6
Clearly, something in my setup is broken. Is it python, gdb, or something
else?
Answer: I'm posting this as an answer so it will be easier for others to find it. The
comments from Mark Plotnick and webbertiger are the actual answer.
To summarize, here is what worked for me:
* Created a ~/.gdbinit file
* Added `python sys.path.append("/usr/share/gcc-4.8/python");` to that file
I'm using Eclipse CDT so I checked that this file is being used in window >
preferences > GDB > GDB command file.
|
Determine where a class is imported from in python
Question: Is there any way to determine where a class is coming from in python
(especially sklearn)? I want to determine if a class is from
sklearn.linear_models or sklearn.ensemble.
As an example, I would like to be able to determine if Ridge() is a member of
sklearn.linear_model.
The fit function is a bit different depending on the model so formulas fed to
each via patsy need to be different.
Answer: Use the `__module__` attribute, i.e.: `Ridge.__module__`
If you want to know it from an instance of the class:
`inst.__class__.__module__`
If you need the module object (not just the name as string):
`sys.modules[Ridge.__module__]`
|
Python os.listdir and path with escape character
Question: I have a string variable that I have read from a file which is a path that
contains an escape character i.e.
dir="...Google\\ Drive"
I would like to then list all the files and directories in that path with
os.listdir i.e.
os.listdir(dir)
But I get this error (because I really only want one escape):
OSError: [Errno 2] No such file or directory: '....Google\\ Drive/'
I have tried using
os.listdir(r'....Google\ Drive')
os.listdir(dir.replace("\\","\"))
os.listdir(dir.decode('string_escape'))
all to no avail. I read this [Python Replace \\\ with
\](http://stackoverflow.com/questions/5186839/python-replace-with), but
"...Google\ drive".decode('string_escape') != "...Google\ Drive".
Any ideas?
Answer: If the path could be arbitrary , you can split the the strings using `\\`
removing any '' you may get along the way and then do `os.path.join` , Example
-
>>> import os.path
>>> l = "Google\Drive\\\\ Temp"
>>> os.path.join(*[s for s in l.split('\\') if l != ''])
'Google\\Drive\\ Temp'
Then you can use that in os.listdir() to list the directories.
|
OverflowError: signed integer is greater than maximum when parsing date in python
Question: When attempting to parse a numerically formatted date:
s ="2506181306"
using the appropriate date format:
DateFormat = '%d%m%H%M%S'
dateutil.parser.parse(s).strftime(DateFormat)
We end up with an _"integer greater than maximum"_ error:
In [15]: dateutil.parser.parse(s).strftime(DateFormat)
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-15-9eead825f5c9> in <module>()
----> 1 dateutil.parser.parse(s).strftime(DateFormat)
/usr/local/lib/python2.7/site-packages/dateutil/parser.pyc in parse(timestr, parserinfo, **kwargs)
1006 return parser(parserinfo).parse(timestr, **kwargs)
1007 else:
-> 1008 return DEFAULTPARSER.parse(timestr, **kwargs)
1009
1010
/usr/local/lib/python2.7/site-packages/dateutil/parser.pyc in parse(self, timestr, default, ignoretz, tzinfos, **kwargs)
402 repl[attr] = value
403
--> 404 ret = default.replace(**repl)
405
406 if res.weekday is not None and not res.day:
OverflowError: signed integer is greater than maximum
So then what is the proper way to parse that date? Is that "greater than
maximum" referring to an individual field within the date - or to the entire
string?
**Update** Jakob provided correct way
In [21]: from datetime import datetime
In [22]: datetime.strptime(s,DateFormat) Out[22]: datetime.datetime(1900, 6,
25, 18, 13, 6)
Answer:
DateFormat = '%d%m%H%M%S'
dateutil.parser.parse(s).strftime(DateFormat)
You're trying to parse this without setting the format first. The error is
thrown from `parse`, the call chain doesn't even make it to the `strftime`
call. It's trying to choose a format that makes sense to it for that string,
and the one it chooses seems to be a unix epoch timestamp, but that's supposed
to be 31 bits (because signed) at most, so it errors.
What you probably want is:
datetime.strptime(s,DateFormat)
|
Is it feasible to unpickle large amounts of data in a Python web app that needs to be scalable?
Question: I am working on my first _web_ application. I am doing it in Python with
Flask, and I want to run a piece of Python code that takes an object, with
Pickle, from a (binary) file of several MB which contains all the necessary
data. I have been told that so using Pickle in a web app is not a good idea
because of scalability; why?
Obviously, for a given purpose it's better to take just the necessary data.
However, if I do this, with an Elasticsearch database and in the fastest way I
can, the whole process takes about 100 times more time than if I take all the
data at once from the binary; once the binary is unpickled, which will take at
most one second, the computations are very fast, so I am wondering if I should
use the binary file, and if so, how to do it in a scalable way.
Answer: So this is something I also have to deal with. In my case it's even worse,
mine can be 100s of MB or more.
My first questions would be:
* Does the pickled data change and if so, where / by whom can it be changed?
* Are there multiple sets of this data that you need? (for me I have 1000s of them needed at different times by different people)
* How often is it needed?
The answers to those questions really raise different ways of approaching it.
Assuming you just have a big blob of stuff that's needed on a bunch of
requests and is the same for everybody, and you know you'll need it soon
enough - I'd load it either when the app starts and keep it in memory or lazy
load it when first requested (and then keep it in memory).
The alternative approach is to split the heavy data bit into its own flask
app.
# api.py: your api flask application
from flask import Flask, jsonify, request
api_app = Flask(__name__)
big_gis_object = unpickle(...)
@api_app.route('/find_distance')
def find_distance():
# grabbing the parameters for this request
lat, lon = request.args['lat'], request.args['lon']
# do your normal geo calculations here
distance = big_gis_object.do_dist_calcs(lat, lon)
# return the result as json to make things easy
return jsonify(distance=distance)
# app.py: your main flask application
import requests
from flask import Flask, render_template
main_app = Flask(__name__)
@main_app.route('/')
def homepage():
# this is how you ask the geo api app to do something for you
# note that we're using the requests library do make it easier
# - http://docs.python-requests.org/en/latest/user/quickstart/
resp = requests.get('http://url_to_flask_app/find_distance', params=dict(lat=1.5, lon=1.7))
distance = resp.json()['distance']
return render_template('homepage.html', distance)
How you then provision those will depend on the load / requirements. It's
flexible though. You can have, say, 40 processes for your main front and just
the 1 api process (though it will only be able to do one thing at a time). If
you need more of the api processes just scale that till you have the right
balance. The tradeoff is that the api processes need more memory.
Does that all make sense?
|
Python paramiko error "TypeError: 'NoneType' object is not iterable" only for a particular computer
Question: While trying to connect to a remote Unix server using `paramiko` I am getting
the error:
> TypeError: 'NoneType' object is not iterable"
Surprisingly, when I try to run the same script, from a different laptop with
same server, username and password, I am able to connect to the server and
execute remote commands.
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect(ftpipaddress,username ='akar',password ='change')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
Absolutely no clue what might be the issue with the laptop having same Python
2.7 and `paramiko` package installed in it. Please help.
Answer: According to the [documentation](http://paramiko-
docs.readthedocs.org/en/latest/api/client.html), `connect` method does not
return anything. In terms of Python, it means, that this method returns
`None`. You are probably looking for `exec_command` method:
>
> exec_command(command, bufsize=-1, timeout=None, get_pty=False)
>
>
> Execute a command on the SSH server. A new Channel is opened and the
> requested command is executed. The command’s input and output streams are
> returned as Python file-like objects representing stdin, stdout, and stderr.
>
> **Parameters:**
>
> * command (str) – the command to execute
>
> * bufsize (int) – interpreted the same way as by the built-in file()
> function in Python
>
> * timeout (int) – set command’s channel timeout. See
> Channel.settimeout.settimeout
>
>
>
> **Returns:** the stdin, stdout, and stderr of the executing command, as a
> 3-tuple
>
> **Raises SSHException:** if the server fails to execute the command
|
Using Biopython SeqIO.convert over an entire directory
Question: I have 51 files with metagenomic sequence data that I would like to convert
from fastq to fasta using a Biopython script in Windows. The module
SeqIO.convert easily converts an individually specified file, but I can't
figure out how to convert the entire directory. It's not really too many files
to do individually, but I'm trying to learn.
I'm brand new to Biopython, so please forgive my ignorance. [This
convo](http://stackoverflow.com/questions/21743438/how-do-i-pass-biopython-
seqio-convert-over-multiple-files-in-a-directory) was helpful, but I'm still
not able to convert the directory from fastq to fasta.
Here's the code I've been trying to run:
#modules-
import sys
import re
import os
import fileinput
from Bio import SeqIO
#define directory
Directory = "FastQ”
#convert files
def process(filename):
return SeqIO.convert(filename, "fastq", "files.fa", filename + ".fasta", "fasta", alphabet= IUPAC.ambiguous_dna)
Answer: You need to iterate over the files in the directory and convert them, so
assuming your directory is `FastQ` and that you are calling your script from
the proper folder (i.e. the one that your directory is in, since you are using
a relative path), you would need to do something like:
def process(directory):
filelist = os.listdir(directory)
for f in filelist:
SeqIO.convert(f, "fastq", f.replace(".fastq",".fasta"), "fasta", alphabet= IUPAC.ambiguous_dna)
then you would call your script in your main:
my_directory = "FastQ"
process(my_directory)
I think that should work.
|
Python Module issues
Question: Im pretty new to python, and have been having a rough time learning it. I have
a main file
import Tests
from Tests import CashAMDSale
CashAMDSale.AMDSale()
and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *
def AMDSale():
AMDInstance = DataFunctions.GetValidAMD()
And here is GetValidAMD
import pyodbc
def ValidAMD(GetValidAMD):
(short method talking to a database)
My error comes up on the line that has `AMDInstance =
DataFunctions.GetValidAMD()`
I get the error `AttributeError: 'module' object has no attribute
'GetValidAMD'`
I have looked and looked for an answer, and nothing has worked. Any ideas?
Thanks!
Answer: When you create the file `foo.py`, you create a python module. When you do
`import foo`, Python evaluates that file and places any variables, functions
and classes it defines into a module object, which it assigns to the name
`foo`.
# foo.py
x = 1
def foo():
print 'foo'
>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo
When you create the directory `bar` with an `__init__.py` file, you create a
python package. When you do `import bar`, Python evaluates the `__init__.py`
file and places any variables, functions and classes it defines into a module
object, which it assigns to the name `bar`.
# bar/__init__.py
y = 2
def bar():
print 'bar'
>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar
When you create python _modules_ inside a python _package_ (that is, files
ending with `.py` inside directory containing `__init__.py`), you must import
these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo
Now, assuming your project structure is:
main.py
DataFunctions/
__init__.py
CashAMDSale.py
def AMDSale(): ...
GetValidAMD.py
def ValidAMD(GetValidAMD): ...
your `main` script can `import DataFunctions.CashAMDSale` and use
`DataFunctions.CashAMDSale.AMDSale()`, and `import DataFunctions.GetValidAMD`
and use `DataFunctions.GetValidAMD.ValidAMD()`.
|
how to use SystemJS to bundle angular TypeScript with internal modules
Question: We are considering moving some of our angular projects over to typescript and
having some trouble with internal module/namespaces.
We posted this working example on github:
<https://github.com/hikirsch/TypeScriptSystemJSAngularSampleApp>
steps:
npm install jspm -g
npm install
cd src/
jspm install
jspm install --dev
cd ..
gulp bundle
cd src/
python -m SimpleHTTPServer
This is the gist of the application: index.ts
/// <reference path="../typings/tsd.d.ts" />
/// <reference path="../typings/typescriptApp.d.ts" />
import * as angular from 'angular';
import {ExampleCtrl} from './controllers/ExampleCtrl';
import {ExampleTwoCtrl} from './controllers/ExampleTwoCtrl';
export var app = angular.module("myApp", []);
app.controller("ExampleCtrl", ExampleCtrl);
app.controller("ExampleTwoCtrl", ExampleTwoCtrl);
ExampleCtrl.ts
/// <reference path="../../typings/tsd.d.ts" />
/// <reference path="../../typings/typescriptApp.d.ts" />
export class ExampleCtrl {
public static $inject:Array<string> = [];
constructor() {
}
public name:string;
public hello_world:string;
public say_hello() {
console.log('greeting');
this.hello_world = "Hello, " + this.name + "!";
}
}
ExampleTwoCtrl.ts
/// <reference path="../../typings/tsd.d.ts" />
/// <reference path="../../typings/typescriptApp.d.ts" />
export class ExampleTwoCtrl {
public static $inject:Array<string> = [];
constructor() {
}
public name:string;
public text:string;
public second() {
this.text = "ExampleTwoCtrl: " + this.name;
}
}
As stated, this works all well and good. But we'd rather have everything under
a namespace like this:
module myApp.controllers {
export class ExampleController {
...
}
}
//do we need to export something here?
and then use it like this:
This will compile correctly running the gulp bundle task but give an error in
the browser /// ///
import * as angular from 'angular';
import ExampleCtrl = myApp.controllers.ExampleCtrl;
import ExampleTwoCtrl = myApp.controllers.ExampleTwoCtrl;
export var app = angular.module("myApp", []);
app.controller("ExampleCtrl", ExampleCtrl);
app.controller("ExampleTwoCtrl", ExampleTwoCtrl);
browser error:
Uncaught ReferenceError: myApp is not defined(anonymous function) @ build.js:5u @ build.js:1i @ build.js:1c @ build.js:1(anonymous function) @ build.js:1(anonymous function) @ build.js:1
build.js:1 Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.3.15/$injector/nomod?p0=myApp
at http://localhost:8000/build/build.js:1:4007
at http://localhost:8000/build/build.js:1:12353
at e (http://localhost:8000/build/build.js:1:11925)
at t.register.e (http://localhost:8000/build/build.js:1:12237)
at http://localhost:8000/build/build.js:1:20741
at o (http://localhost:8000/build/build.js:1:4392)
at p (http://localhost:8000/build/build.js:1:20519)
at Bt (http://localhost:8000/build/build.js:1:22209)
at t.register.s (http://localhost:8000/build/build.js:1:10038)
at Q (http://localhost:8000/build/build.js:1:10348)
http://errors.angularjs.org/1.3.15/$injector/modulerr?p0=myApp&p1=Error%3A%…0%20at%20Q%20(http%3A%2F%2Flocalhost%3A8000%2Fbuild%2Fbuild.js%3A1%3A10348)
Answer: According to [typescript
documentation](https://github.com/Microsoft/TypeScript/wiki/Modules#needless-
namespacing) you do not need to use internal modules when compiling to
commonjs. As stated:
> A key feature of external modules in TypeScript is that two different
> external modules will never contribute names to the same scope. Because the
> consumer of an external module decides what name to assign it, there's no
> need to proactively wrap up the exported symbols in a namespace.
I have found the best way to use typescript with a commonjs loader (I am using
browserify) is to do something like:
class ExampleTwoCtrl {
public static $inject:Array<string> = [];
constructor() {
}
public name:string;
public text:string;
public second() {
this.text = "ExampleTwoCtrl: " + this.name;
}
}
export = ExampleTwoCtrl
and the use it like:
import MyController = require('./ExampleTwoCtrl');
var a = new MyController();
That being said, I watched the recording from [John Papa's talk at
AngularU](https://angularu.com/VideoSession/2015sf/dan-and-john-bringing-
their-view-on-the-latest-in-angular) where they demonstrated some code bundled
using systemjs written in typescript without any imports, just internal ts
modules. I asked on twitter where I could find the sample code, but haven't
got a response yet.
|
Python Division Many Decimal Places
Question: Hi I'm wondering how to get python to output an answer to many more decimal
places than the default value.
For example: Currently print(1/7) outputs: 0.14285714285
I want to be able to output:0.142857142857142857142857142857142857142857142857
Answer: If you want completely arbitrary precision (which you will pretty much need to
get at that level of precision), I recommend looking at the
[`mpmath`](http://mpmath.org/) module.
>>> from mpmath import mp
>>> mp.dps = 100
>>> mp.fdiv(1.0,7.0)
mpf('0.1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428579')
I suppose if all you want is to be able to do very simple arithmetic, the
builtin `decimal` module will suffice. I would still recommend `mpmath` for
anything more complex. You could try something like this:
>>> import decimal
>>> decimal.setcontext(decimal.Context(prec=100))
>>> decimal.Decimal(1.0) / decimal.Decimal(7.0)
Decimal('0.1428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571428571429')
|
ImportError: no module named guardian
Question: I'm new to Django, so generally I am the cause of most of my problems, but I
can't figure out why the django-guardian 1.3 app won't install. I'm using
Django 1.7 in a virtual environment, my OS is Windows 8.1.
I followed the installation directions at [pythonhosted.org/django-
guardian/installation.html](http://pythonhosted.org/django-
guardian/installation.html) and configuration at [pythonhosted.org/django-
guardian/configuration.html](http://pythonhosted.org/django-
guardian/configuration.html), but I get an error when I attempt to run the
program.
I added 'guardian', ANONYMOUS_USER_ID, and the backends to my settings.py
"""
Django settings for VolunteerManager project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'Super Super Secret'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
ANONYMOUS_USER_ID = -1
# Application definition
INSTALLED_APPS = (
#DEFAULT APPS
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#THIRD PARTY APPS
'guardian',
'registration',
#Copyright (c) 2007-2012, James Bennett
#All rights reserved.
'django.contrib.sites',
#LOCAL APPS
'Volunteer',
)
ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window;
REGISTRATION_AUTO_LOGIN = True # Automatically log the user in.
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
)
ROOT_URLCONF = 'VolunteerManager.urls'
#ANONYMOUS_USER_ID = 'VOLUNTEER_USER_ID'
WSGI_APPLICATION = 'VolunteerManager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'volunteer',
'USER': 'root',
'PASSWORD': '$',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
LOGIN_REDIRECT_URL = '/home/'
SITE_ID = 1
[Error picture available on IMGUR](http://i.imgur.com/aJejJjO.png)
Django-guardian appears to be installed in my virtual environment, but it's
still not finding it. Any ideas what I might have done wrong? (Or other
suggestions for per-object permissions in Django?) Thank You!
UPDATE: I narrowed the problem down to the virtualenv. When I installed the
modules without using virtualenv, then django finds them like it should. I'm
still not sure what exactly I did wrong, but this works for now, considering
that I'm only working on one project at the moment.
Answer: > I narrowed the problem down to the virtualenv. When I installed the modules
> without using virtualenv, then django finds them like it should.
You need to activate the virtual environment each time your run django,
otherwise you'll continue to run into issues like what you have described.
Activating the virtual environment (by executing `Scripts\activate.bat`) sets
the correct environment variables to that all Python commands are run against
the virtual environment's Python installation.
If you do not run the `activate.bat` file before running Python commands, they
will be executed against the system-wide Python installation.
The reason django it works is because you are running django without the
virtualenv activated; and you also happen to have django installed in the
global Python environment.
|
ImportError: No module named concurrent.futures.process
Question: I have followed the procedure given in [How to use valgrind with
python?](http://stackoverflow.com/questions/20112989/how-to-use-valgrind-with-
python) for checking memory leaks in my python code.
I have my python source under the path
/root/Test/ACD/atech
I have given above path in `PYTHONPATH`. Everything is working fine if I run
the code with default python binary, located under `/usr/bin/`. I need to run
the code with the python binary I have build manually which is located under
/home/abcd/workspace/pyhon/bin/python
Then I am getting the following error
from concurrent.futures.process import ProcessPoolExecutor
ImportError: No module named concurrent.futures.process
How can I solve this?
Answer: If you're using Python 2.7 you must install this module :
pip install futures
Futures feature has never included in Python 2.x core. However, it's present
in Python 3.x since Python 3.2.
|
Some Decoding Issue With String in Python
Question: I'm trying to write the HTML Code string from Google into file in Python 3.4
#coding=utf-8
try:
from urllib.request import Request, urlopen # Python 3
except:
from urllib2 import Request, urlopen # Python 2
useragent = 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'
#Generate URL
url = 'https://www.google.com.tw/search?q='
query = str(input('Google It! :'))
full_url = url+query
#Request Data
data = Request(full_url)
data.add_header('User-Agent', useragent)
dataRequested = urlopen(data).read()
dataRequested = str(dataRequested.decode('utf-8'))
print(dataRequested)
#Write Data Into File
file = open('Google - '+query+'.html', 'w')
file.write(dataRequested)
It can print the string correctly, but when it write to file, it will show
file.write(dataRequested)
UnicodeEncodeError: 'cp950' codec can't encode character '\u200e' in position 97658: illegal multibyte sequence
I tried to change the decode way but it doesn't work. And i tried to replace
\u200e too,but it will comes more encode charater error.
Answer: Your problem is
> dataRequested = str(dataRequested.decode('utf-8'))
Is there a reason to convert decoded UTF-8 into a string? But that is not all.
When you get a string from the Internet it should be decoded but when you save
the string it should be encoded. Some guys don't get it. They either decode or
encode. It doesn't work this way.
I altered your code a bit. It works fine for me on both Python2.7 and
Python3.4.
dataRequested = dataRequested.decode('utf-8')
print(dataRequested)
#Write Data Into File
file = open('Google - '+query+'.html', 'wb')
file.write(dataRequested.encode('utf-8'))
|
Python functional closures without performance hit
Question: In my python program, I have a ton of functions that are really wrappers for
more complicated functions (the more complicated functions take more
arguments, so the simple functions calculate the extra arguments and pass them
along with the original arguments to the complex functions). I don't want the
more complicated functions to be visible from the outer scope. However, my
understanding is that if you define a function inside a function every time
the outer function gets called it redefines the inner function, which is
wasteful. How can I hide my inner functions without redefining them over and
over again? There must be some way for the interpreter to parse my file and
just do the definitions once but still keep them in the inner scope.
Answer: Rather than controlling access to your _"inner functions"_ by nesting them,
use either or both of:
* naming conventions (a leading underscore on a name means private-by-convention, see [the style guide](https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables)); and
* defining a list named `__all__` to specify what gets imported from the package by default (see [the tutorial on modules](https://docs.python.org/2/tutorial/modules.html#importing-from-a-package)).
In use:
# define the names that get imported from this package
__all__ = ['outer_func']`
def _inner_func(...):
"""Private-by-convention inner function."""
...
def outer_func(...):
"""Public outer function to call _inner_func."""
...
This makes testing much easier, too, as you can still get direct access to
`_inner_func` when necessary.
|
Passing data for Curl Function to a Python program on Bash
Question: So I'm trying to extract data from the curl function as listed on this Asana
API. <https://asana.com/developers/api-reference/projects>. The problem is
that the data I receive looks like this
{"data":[{"id":"1000","name","first thing"},{"id":"1001","name","second
thing"}, {"id":"1002","name","third thing"}]}
This is a great dictionary organized really nicely, but I'm unable to actually
use it because bash doesn't recognize this as a dictionary. It is simply
reading it as a string. I'm very familiar with python, so I thought if I pass
it to a python program it will recognize it as a dictionary, but it doesn't.
Please help. All I need is to be able to establish the data as a dictionary
and array as it should be. After that I can work with it as I want.
This is what I have so far.
READFILE=$(curl -u $KEY: https://app.asana.com/api/1.0/projects)
echo $READFILE
if I try to do something like this, however,
for dict in ${READFILE["data"]};
do echo $dict
echo ABC
done
bash returns splits the data by white space, so it'll look like this
{"data":[{"id":"1000","name","first
ABC
thing"},{"id":"1001","name","second
ABC
thing"},{"id":"1002","name","third
ABC
thing"}]}
ABC
Similarly if I pass this to a external python script like this
python work.py $READFILE
and I try to print like this
import sys
print(sys.argv);
I'll get
{"data":[{"id":"1000","name","first
Help me get Python to receive the actual data structure, not just a string
split at whitespaces.
Answer: There is a [python api](https://github.com/Asana/python-asana) for asana so
you can so it all using python:
# basic auth
client = asana.Client.basic_auth('ASANA_API_KEY')
# oauth 2
client = asana.Client.oauth(
client_id='ASANA_CLIENT_ID',
client_secret='ASANA_CLIENT_SECRET',
redirect_uri='https://yourapp.com/auth/asana/callback'
)
There are numerous examples in the link above.
|
Inca Open Experiment Python
Question: I am working on python and i need to use a Tool named "Inca". Now i am able to
run remotely this tool but i can't to open an experiment located in a specific
workspace.
import sys,clr
sys.path.append("*path*")
clr.AddReference("incacom")
from de.etas.cebra.toolAPI.Inca import*
targetFolder = None
myDB = None
tempItemm = None
a = Inca()
myDB = a.GetCurrentDataBase()
tempItem = myDB.GetItemInFolder("*par1"*, "*par2*")
w = myDB.GetActivehardwareConfiguration()
exp = w.GetAssignedExperimentEnviroment()
e = exp.OpenExperiment()
Answer: It looks like you have a configuration problem. Either you don't have an
active hardware configuration, or an experiment environment wasn't assigned to
it. As a result, one of your calls returns `None`, which you don't check for,
and the next call fails because `NoneType` doesn't have the method you expect.
Nevertheless, if you know the name of your experiment environment, you can
always find it via `BrowseItem` call on your Inca database:
a.GetCurrentDataBase().BrowseItem('MyExperiment')[0].OpenExperiment()
|
Python scrapy spider
Question: I want to scrape data from a website http://www.quoka.de/immobilien/bueros-
gewerbeflaechen with this filter:
<a class="t-bld" rel="nofollow" href="javascript:qsn.set('classtype','of',1);">nur Angebote</a>
How to set this filter using scrapy?
Answer: You can parse a specific website by using `Beautifulsoup`and `urllib2`. Here
is a python implementation for the data that you wanted to parse or scrape
according to the filter you wrote.
from BeautifulSoup import BeautifulSoup
import urllib2
def main1(website):
data_list = []
web =urllib2.urlopen(website).read()
soup = BeautifulSoup(web)
description = soup.findAll('a', attrs={'rel':'nofollow'})
for de in description:
data_list.append(de.text)
return data_list
print main1("http://www.quoka.de/immobilien/bueros-gewerbeflaechen")
If you wanted to parse other data such as the description from the following:

def main(website):
data_list = []
web =urllib2.urlopen(website).read()
soup = BeautifulSoup(web)
description = soup.findAll('div', attrs={'class':'description'})
for de in description:
data_list.append(de.text)
return data_list
print main("http://www.quoka.de/immobilien/bueros-gewerbeflaechen") #this is the data of each section
|
Changing GET to POST in Python (Flask)
Question: I am trying to create a simple app where an array of integers is generated on
the server and sent to the client. Here is some sample (working) code in
app.py:
from flask import Flask, render_template, request, url_for
import random
app = Flask(__name__)
@app.route('/')
def form():
s_abc = [random.random() for _ in range(40)]
return render_template('abc.html', s_abc=s_abc)
if __name__ == '__main__':
app.run(debug=True)
And here is a (working) snippet of abc.html:
<div>
{{s_abc}}
</div>
The problem is, this code uses the GET HTTP method (which Flask uses by
default when none is specified). I would like to instead use the POST HTTP
method, since it is apparently more secure for sending data. (Source:
<http://blog.teamtreehouse.com/the-definitive-guide-to-get-vs-post>)
To do this, I tried to change:
@app.route('/')
to:
@app.route('/', methods=['POST'])
Unfortunately, I got an error: "Method Not Allowed: The method is not allowed
for the requested URL."
Question: How should I fix this?
[Note: From what I currently understand, I would need to create a form to use
the POST method, but I don't think my website would need a form, since the
client isn't sending data to the server. (In my website, the server is sending
data to the client.)]
[Note: This is similar to a question I asked previously, but not the same,
because here I am asking about a specific error message, Method not Allowed.]
Answer: When you use the browser to visit a page, the browser always send 'GET'
request to server... so when you've changed the methods to 'POST', flask can't
find any GET route for '/' and return "Method Not Allowed" error, as the '/'
doesn't allows GET anymore when browsers asks for that page.
You shouldn't use POST for this. POST only used when submitting data from
forms or ajax.
|
how to pass value from output to a string in python
Question: I've been trying to make an application in python and I'm new to python. Well,
what I actually want to do is that . I want the feedparser to read the values
from an RSS of a website... say reddit... and then I want to make that output
as a stringand pass the value further to my code... my code right now..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
It is working right now.. it parses the feed and I get the output I want...
Now, I want to use the "link" from the "print feed['entries'][1]['link'] " and
use it in the code further... how can I do so..? To be more specific.. I want
to open that URL in my browser... I concluded to something like this..
import feedparser
import webbrowser
feed = feedparser.parse('http://www.reddit.com/.rss')
print feed['entries'][1]['title']
print feed['entries'][1]['link']
mystring = 'feed['entries'][1]['link']'
webbrowser.open('mystring')
It is of course not working... Please Help... if you need to know anything
else.. please let me know...
Answer: This is Reddit specific so it won't work on other RSS feeds but I thought this
might help you.
from __future__ import print_function
import praw
r = praw.Reddit("my_cool_user_agent")
submissions = r.get_front_page()
for x in submissions:
print("Title: {0} URL: {1} Permalink: {2}".format(x, x.url, x.permalink))
print ("------------------------------------------------------------")
For Reddit there are 2 URLs that you might be interested in: the actual link
that is submitted (the 'external' link... think imgur, etc) and the permalink
to the Reddit post itself.
|
share a global variable in multi threading doesn't work in python
Question: I am trying to share a global variable between two function in `python`. They
are working at the same time whith multitreading. the problem is that its like
the global variable is not global at all here is my code:
import threading as T
import time
nn = False
def f1(inp):
global nn
while True:
inp=inp+1
time.sleep(0.5)
print 'a-'+str(inp)+"\n"
if inp > 10:
nn=True
print nn
def f2(inp):
inp=int(inp)
while nn:
inp=inp+1
time.sleep(1)
print 'b-'+str(inp)+"\n"
t1= T.Thread(target=f1, args = (1,))
t1.daemon = True
t1.start()
t2= T.Thread(target=f2, args = (1,))
t2.daemon = True
t2.start()
Answer: The problem is that `while nn` only gets evaluated once. When it is, it
happens to be `False` because f1 has not yet made it `True` so `f2` finishes
running. If you initialize `nn = True` you'll see it is being accessed by both
`f1` and `f2`
|
Getting started with Python OCR on windows?
Question: I have never used python before, and I am not sure where to start. My goal is
to take image data, of numbers and multicolored background, and reliably get
the correct characters identified. I looked into the tools necessary for this
and I found the Anaconda python distribution which included all the possible
packages I might need for this, as well as tesseract-ocr and pytesser.
Unfortunately, I'm lost in how to begin. I"m using the PyCharm Community IDE
and simply trying to follow this guide:
<http://www.manejandodatos.es/2014/11/ocr-python-easy/> to get a grasp on OCR.
This is the code I'm using:
from PIL import Image
from pytesser import *
image_file = 'menu.jpg'
im = Image.open(image_file)
text = image_to_string(im)
text = image_file_to_string(image_file)
text = image_file_to_string(image_file, graceful_errors=True)
print "=====output=======\n"
print text
and I believe the Anaconda distribution that I'm using has PIL, but I'm
getting this error:
C:\Users\diego_000\Anaconda\python.exe C:/Users/diego_000/PycharmProjects/untitled/test.py
Traceback (most recent call last):
File "C:/Users/diego_000/PycharmProjects/untitled/test.py", line 2, in <module>
from pytesser import *
File "C:\Users\diego_000\PycharmProjects\untitled\pytesser.py", line 6, in <module>
import Image
ImportError: No module named Image
Process finished with exit code 1
Can anyone point me in the right direction?
Answer: The document you point to says to use
from PIL import Image
except you use
import Image
and so the interpreter properly says:
ImportError: No module named Image
It looks as if you reordered the lines
from PIL import Image
from pytesser import *
and that pytesser has a improperly coded dependency on PIL. but I can't be
certain with the code you provided.
|
Python reading from stdin hangs when interacting with ruby code
Question: I was trying to put python and ruby codes into conversation, and I found the
methods from this link (<http://www.decalage.info/python/ruby_bridge>)
I tried the last method, using stdin and stdout to pass information. I made
some changes to the origin code so that it fits python 3.4, but I am not sure
whether or not the code that I changed messed all the things up. My python
program always hangs when reading from stdin, and nothing was printed. I am
not familiar with stdin and stdout, so I am just wondering why this does not
work.
Here are my ruby codes:
$stdin.set_encoding("utf-8:utf-8")
$stdout.set_encoding("utf-8:utf-8")
while cmd = $stdin.gets
cmd.chop!
if cmd == "exit"
break
else
puts eval(cmd)
puts "[end]"
$stdout.flush
end
end
I am not sure if it is possible to set internal encoding and external encoding
like this. And here are my python codes:
from subprocess import Popen, PIPE, STDOUT
print("Launch slave process...")
slave = Popen(['ruby', 'slave.rb'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
while True:
line = input("Enter expression or exit:")
slave.stdin.write((line+'\n').encode('UTF-8'))
result = []
while True:
if slave.poll() is not None:
print("Slave has terminated.")
exit()
line = slave.stdout.readline().decode('UTF-8').rstrip()
if line == "[end]":
break
result.append(line)
print("result:")
print("\n".join(result))
When I try to run the python script, input "3*4", and press enter, nothing
shows until I broke the process manually with exit code 1 and
KeyboardInterrupt Exception. I have been struggling with this problem for
quite a long time and I don't know what goes wrong... Thanks in advance for
any potential help!
Answer: The difference is that `bufsize=-1` by default in Python 3.4 and therefore
`slave.stdin.write()` does not send the line to the `ruby` subprocess
immediately. A quick fix is to add `slave.stdin.flush()` call.
#!/usr/bin/env python3
from subprocess import Popen, PIPE
log = print
log("Launch slave process...")
with Popen(['ruby', 'slave.rb'], stdin=PIPE, stdout=PIPE,
bufsize=1, universal_newlines=True) as ruby:
while True:
line = input("Enter expression or exit:")
# send request
print(line, file=ruby.stdin, flush=True)
# read reply
result = []
for line in ruby.stdout:
line = line.rstrip('\n')
if line == "[end]":
break
result.append(line)
else: # no break, EOF
log("Slave has terminated.")
break
log("result:" + "\n".join(result))
It uses `universal_newlines=True` to enable text mode. It uses
`locale.getpreferredencoding(False)` to decode bytes. If you want to force
`utf-8` encoding regardless of locale settings then drop `universal_newlines`
and wrap the pipes into `io.TextIOWrapper(encoding="utf-8")` ([code example --
it also shows the proper exception handling for the
pipes](http://stackoverflow.com/a/28300123/4279)).
|
How do I use cx_Freeze on mac?
Question: I used python 3.4 and cx_Freeze on my mac. I was trying to convert my python
script into a stand alone application here is the code I got in my setup.py
file:
application_title = "Death Dodger 1.0"
main_python_file = "DeathDodger-1.0.py"
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includes = ["atexit","re"]
setup(
name = application_title,
version = "1.0",
description = "Sample cx_Freeze script",
options = {"build_exe" : {"includes" : includes }},
executables = [Executable(main_python_file, base = base)])
I typed in these lines of code into my Terminal:
cd /Users/HarryHarlow/Desktop/Death_Dodger
and I typed in this line after:
python3.4 setup.py bdist_mac
I got this error message after long lines of other results:
error: [Errno 2] No such file or directory: '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl'
Please help, I've been stuck on this for **3 weeks** ,thank you.
Answer: If you don't need Tcl you can exclude it in the setup file:
application_title = "Death Dodger 1.0"
main_python_file = "DeathDodger-1.0.py"
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includes = ["atexit","re"]
setup(
name = application_title,
version = "1.0",
description = "Sample cx_Freeze PyQt4 script",
options = {
"build_exe" : {
"includes" : includes
"excludes": ['tcl', 'ttk', 'tkinter', 'Tkinter'],
}
},
executables = [
Executable(main_python_file, base = base)
]
)
I excluded also Tkinter since as far as I can understand you are making use of
PyQt4 to draw the user interface.
|
Remove HTML child inside its parent
Question: I have some HTML like this:
<ul>
<li>Item 1</li><br>
<li>Item 2</li><br>
<li>Item 3</li><br>
</ul>
<img src="someImage.png"><br>
And I would like to remove the `<br>` tags from after the `<li>` tags and the
`<img>` tags using regex though I'm not sure how to go about this. The HTML
does not remain the same, so the image and lists may be in a different
location or there may be other content though there will always be a `<br>`
after a `</li>` and `</img>`
What regex could I use to solve this with python? Thanks.
**Edit:**
I tried using this `(<img.+?>)<br>` for the image but it did not work.
I don't want to just simply remove ALL of the `<br>` tags because there may be
some useful ones in the HTML, rather I would like to have the ones after the
list items and images removed.
Answer: This is one way to remove the `br` tags:
import re
print re.sub('<br>', "", '<li>Item 1</li><br>')
If there are many `br` tags in your document you have to store the data in a
variable like this:
data = 'your full html document as a string'
print re.sub('<br>', "", data)
Then this will remove all the `br` tags in the entire `data` document.
If you only want to remove the `br` tags that are after the `li` tags then you
can do it like this:
data = 'your full html document as a string'
print re.sub(r'^<li>\<br>', "", data)
|
scapy sniff function not catching any packets
Question: I've been following Seitz's black hat python book and he gives an example of
capturing network traffic using the scapy library.
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
def packet_callback(packet):
print packet.show()
sniff(filter="",iface="any",prn=packet_callback, count = 1)
I run the above function as follows: `sudo python sniffer.py` and open google
chrome to a page. No packets get captured. I do a ping request to a domain and
nothing gets captured. I was expecting the `print packet.show()` line to print
the first packet being sent.
All of this is being run on a Macbook Pro on a wireless internet connection.
Can someone help me troubleshoot?
Answer: if you want scapy to sniff on all interfaces, just remove the iface = "any"
parameter. Since "any" is not an interface therefore scapy cannot sniff.
Also remove the filter parameter since it is not applying any filter. The
correct command would like like this.
sniff(prn=packet_callback, count = 1)
|
Python requests module : Post and go to next page
Question: I'm filling a form on a web page using python's request module. I'm submitting
the form as a POST request, which works fine. I get the expected response from
the POST. However, it's a multistep form; after the first "submit" the site
loads another form on the same page (using AJAX) . The post response has this
HTML page . Now, how do I use this response to fill the form on the new page?
Can I intertwine Requests module with Twill or Mechanize in some way?
Here's the code for the POST:
import requests
from requests.auth import HTTPProxyAuth
import formfill
from twill import get_browser
from twill.commands import *
import mechanize
from mechanize import ParseResponse, urlopen, urljoin
http_proxy = "some_Proxy"
https_proxy = "some_Proxy"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy
}
auth = HTTPProxyAuth("user","pass")
r = requests.post("site_url",data={'key':'value'},proxies=proxyDict,auth=auth)
The response `r` above, contains the new HTML page that resulted from
submitting that form. This HTML page also has a form which I have to fill. Can
I send this `r` to twill or mechanize in some way, and use Mechanize's form
filling API? Any ideas will be helpful.
Answer: The problem here is that you need to actually interact with the javascript on
the page. `requests`, while being an excellent library has no support for
javascript interaction, it is just an http library.
If you want to interact with javascript-rich web pages in a meaningful way I
would suggest [selenium](https://selenium-python.readthedocs.org/). Selenium
is actually a full web browser that can navigate exactly as a person would.
The main issue is that you'll see your speed drop precipitously. Rendering a
web page takes a lot longer than the raw html request. If that's a real deal
breaker for you you've got two options:
* Go headless: There are many options here, but I personally prefer [casper](http://casperjs.org/). You should see a ~3x speed up on browsing times by going headless, but every site is different.
* Find a way to do everything through http: Most non-visual site functions have equivalent http functionality. Using the google developer tools network tab you can dig into the requests that are actually being launched, then replicate those in python.
As far as the tools you mentioned, neither `mechanize` nor `twill` will help.
Since your main issue here is javascript interaction rather than cookie
management, and neither of those frameworks support javascript interactions
you would run into the same issue.
UPDATE: If the post response is actually the new page, then you're not
actually interacting with AJAX at all. If that's the case and you actually
have the raw html, you should simply mimic the typical http request that the
form would send. The same approach you used on the first form will work on the
second. You can either grab the information out of the HTML response, or
simply hard-code the successive requests.
|
Properly handling exceptions in Python and exit class execution
Question: How to handle inside class execution errors? return something so an outside
function knows that and call the class with other data. What will be the
proper way to do this in Python?
I understand we can handle all exceptions by doing the following:
import sys
try:
do_something()
except Exception:
do_something_else()
system.exit('Something happened')
and the line "`system.exit('Something happened')`" will exit Python. The thing
is that I have a class, with three methods plus the `__init__()` method. In
total four methods or functions. And I have a function that calls this
**class** with different values and the class performs its actions. I'm not
doing any exception handling in the class because I have no idea how to do so.
Here's what my class looks like.
class myClass:
def __init__(self, values, more values):
config = []
answer = self.first_method(values)
if answer == True:
self.third_method(values, more_values, answer)
def first_method(values):
my_tuple = self.second_method(values)
return my_tuple
def second_method(values)
do_stuff
return stuff
def third_method(values, more_values, answer):
do_stuff...
outside function will look like:
from my myclass import myClass
def my_function():
count = 0
more_values = [6,7,8,9,10]
list_of_values = [1,2,3,4,5]
for values in list_of_values:
myClass(values, more_values)
count += 1
and what I need is that, if something happens in the `first_method()`,
`second_method()`, and `third_method()`.I will need the class to be stopped
and return something so the outside function will know that the class has been
stopped by something and skip that one and try next one. Did I make myself
clear enough? I don't show the code from my class because I'm still working on
the class itself and also the outside function. But that's the main idea.
Something that might be important: What I'm trying to perform is to create
some images and I'm using PIL. I've been importing the following:
from PIL import Image, ImageFont, ImageOps, ImageDraw
Answer: Based on my comment about avoiding classes where you don't really need them,
try going about it this way:
def start(values, more values):
config = []
answer = runfirst(values)
if answer == True:
runthird(values, more_values, answer)
def runfirst(values):
my_tuple = runsecond(values)
return my_tuple
def runsecond(values):
do_stuff
return stuff
def runthird(values, more_values, answer):
do_stuff...
Then, in your "outside" function:
from myfunctions import start
def my_function():
count = 0
more_values = [6,7,8,9,10]
list_of_values = [1,2,3,4,5]
for values in list_of_values:
try:
start(values, more_values)
except (ValueError, IndexError) as exc:
print("Houston, we've had a problem:", exc)
continue
count += 1
No class necessary: all your first, second and third functions are stowed away
neatly in their own module, and don't need a class.
Note: never catch _every_ exception with the generic `except Exception`. Catch
specific exceptions. Because there is always that one exception you overlooked
that you really want to bubble up all the way.
|
How do I do a jointplot in R the same way as I do it python (seaborn package)
Question: How do I do a jointplot in R the same way as I do it python (seaborn package)
In python
import seaborn as sns
sns.jointplot(bigdiamonds["price"], bigdiamonds["carat"])
<seaborn.axisgrid.JointGrid at 0x207230b0>

How do I do this in R?
Answer: Thanks Marius
I did this from the blog post
devtools::install_github("WinVector/WVPlots")
library(WVPlots)
ScatterHist(diamonds, "price", "carat")
and got this

|
DNS resolving in C/C++
Question: In python I can work with DNS like this:
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dns.resolver
>>> answer = dns.resolver.query('www.example.com')
>>> print answer.response
id 37102
opcode QUERY
rcode NOERROR
flags QR RD RA
;QUESTION
www.example.com. IN A
;ANSWER
www.example.com. 3600 IN A 93.184.216.34
;AUTHORITY
;ADDITIONAL
>>> print answer.rrset
www.example.com. 3600 IN A 93.184.216.34
>>>
What's the easiest way to achieve the same result in C/C++? Either using a
library (which one most popular?) or sending the request manuall via sockets
or something.
Answer: Start with [getaddrinfo](http://linux.die.net/man/3/getaddrinfo). Then the
[res_* functions](http://linux.die.net/man/3/resolver) for advanced queries.
These other functions might be useful to you as well.
[gethostbyname](http://linux.die.net/man/3/gethostbyname)
[getnameinfo](http://linux.die.net/man/3/getnameinfo)
[gethostent](http://linux.die.net/man/3/gethostent)
|
Error while running the sample display image program in python OpenCV
Question: I am getting an error when I run the following sample display image program in
my Dell Inspiron 15R windows 8.1 64 bit system
import numpy as np
import cv2
img = cv2.imread('G:/space.jpg',0)
cv2.imshow('image',img)
cv2.waitKey(0) & 0xFF
cv2.destroyAllWindows()
And the error which I am getting at the command prompt is:
> Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All
> rights reserved.
>
> C:\Users\Ankit>python G:/messi.py
>
> OpenCV Error: Bad flag (parameter or structure field) (Unrecognized or
> unsupported array type) in unknown function, file
> C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array.cpp, line
> 2482
>
> Traceback (most recent call last):
>
> File "G:/messi.py", line 5, in
>
>
> cv2.imshow('image',img)
>
>
> cv2.error:
> C:\slave\WinInstallerMegaPack\src\opencv\modules\core\src\array.cpp:2
>
> 482: error: (-206) Unrecognized or unsupported array type
Please help! I am a novice in opencv.
Answer: Apparently the image couldn't be read. You might want to `print img` to check
if it's valid. See [the `imread`
documentation](http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html#imread)
for more information.
|
GMail API returns unspeficied error at random moments
Question: I'm running a Python app on Google App Engine which regularly checks the
latest emails for multiple users. I've noticed that at random moments, the API
returns the following error:
error: An error occured while connecting to the server: Unable to fetch URL: https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest?userIp=0.1.0.2
Typically, if the job runs again, it works. Below my code. I would like to
understand what is causing this, and more importantly how I can prevent the
error from blocking the process (e.g. how to run the job again with the same
values when this error is thrown).
class getLatest(webapp2.RequestHandler):
def post(self):
try:
email = self.request.get('email')
g = Credentials.get_by_id(email)
REFRESH_TOKEN = g.refresh_token
start_history_id = g.hid
credentials = OAuth2Credentials(None, settings.CLIENT_ID,
settings.CLIENT_SECRET, REFRESH_TOKEN, None,
GOOGLE_TOKEN_URI, None,
revoke_uri=GOOGLE_REVOKE_URI,
id_token=None,
token_response=None)
http = credentials.authorize(httplib2.Http())
service = discovery.build("gmail", "v1", http=http)
for n in range(0, 5):
try:
history = service.users().history().list(userId=email, startHistoryId=start_history_id).execute(http=http)
break
except errors.HttpError, e:
if n < 4:
time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
else:
raise
changes = history['history'] if 'history' in history else []
while 'nextPageToken' in history:
page_token = history['nextPageToken']
for n in range(0, 5):
try:
history = service.users().history().list(userId=email, startHistoryId=start_history_id, pageToken=page_token).execute(http=http)
break
except errors.HttpError, e:
if n < 4:
time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
else:
raise
changes.extend(history['history'])
except errors.HttpError, error:
logging.exception('An error occurred: '+str(error))
if error.resp.status == 401:
# Credentials have been revoked.
# TODO: Redirect the user to the authorization URL.
raise NotImplementedError()
else:
stacktrace = traceback.format_exc()
logging.exception('%s', stacktrace)
UPDATE
I updated the code based on the answer below, however it never seems to run
the request multiple times. The process just aborts as soon as an exception
takes place.
Answer: This error can occur due to multiple reasons including your agent going
offline for a moment to exceeding rate limit of Gmail API. You need to retry
in case of these temporary issues in a graceful manner. Below is the code edit
that may help:
class getLatest(webapp2.RequestHandler):
def post(self):
try:
email = self.request.get('email')
g = Credentials.get_by_id(email)
REFRESH_TOKEN = g.refresh_token
start_history_id = g.hid
credentials = OAuth2Credentials(None, settings.CLIENT_ID,
settings.CLIENT_SECRET, REFRESH_TOKEN, None,
GOOGLE_TOKEN_URI, None,
revoke_uri=GOOGLE_REVOKE_URI,
id_token=None,
token_response=None)
http = credentials.authorize(httplib2.Http())
service = discovery.build("gmail", "v1", http=http)
for n in range(0, 5):
try:
history = service.users().history().list(userId=email, startHistoryId=start_history_id).execute(http=http)
break
except Exception as e:
# Apply exponential backoff.
time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
changes = history['history'] if 'history' in history else []
while 'nextPageToken' in history:
page_token = history['nextPageToken']
for n in range(0, 5):
try:
history = service.users().history().list(userId=email, startHistoryId=start_history_id, pageToken=page_token).execute(http=http)
changes.extend(history['history'])
break
except Exception as e:
# Apply exponential backoff.
time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
except errors.HttpError, error:
logging.exception('An error occurred: '+str(error))
if error.resp.status == 401:
# Credentials have been revoked.
# TODO: Redirect the user to the authorization URL.
raise NotImplementedError()
else:
stacktrace = traceback.format_exc()
logging.exception('%s', stacktrace)
Essentially this code retries if an exception occurs at google end from the
same point with exponential backoff. Add your error code, for which you want
to retry. Hope this resolves your problem.
|
Reading a file and using a loop to output the integers while displaying the largest number python
Question: The program should output all of the integers, one per line, with no blank
lines between each line. This program should also output the largest random
number that was on file.
myfile = open('mynumbers.txt', 'r')
lines = myfile.readline()
print(lines)
I have gotten that far and I'm stuck. I have literally been sitting here for 6
hours and I don't know what the deal is!
I need help using a loop to read and process the `mynumbers.txt` file and then
it also has to display the largest number that was in the group.
myfile = open('mynumbers.txt', 'w')
import random
num = random.randint(6, 12)
print(num)
for num in range(num):
myfile.write(str(random.randrange(10, 20)))
I also keep getting this error after I try everything.
ValueError: invalid literal for int() with base 10: '16 19 11 18 14 11 15 18
18 16 20 16'
Sorry everyone i'm new to the site!
Answer: `.readline()` only read **one** line.
You should use `.readlines()` if you want to get all the lines of your file.
Moreover, it is better to open your file using `with`.
with open('filename.txt') as fp:
lines = fp.readlines()
# Do something with the lines
See [the
documentation](https://docs.python.org/3.4/tutorial/inputoutput.html#methods-
of-file-objects) for more information.
|
How to use the login session for another http request in python?
Question: We have an application which does not support basic authentication yet. So I
wrote a python script which sends a post request to login and then another
request to a web service url. When I make the second call, my server is asking
me to login again.
How can I use the same session to make the second call? Is it really possible?
Below is the script
import requests
r = requests.post("https://myhost.com/login", verify=False, data={'IDToken1': 'administrator', 'IDToken2': 'TestPassw0rd', 'goto': 'https://myhost.com/', 'gotoInactive': 'https://myhost.com/login/?goto=https%3A%2F%2Fmyhost.com&login=inactive&user=administrator', 'gotoOnFail': 'https://myhost.com/login/?goto=https%3A%2F%2Fmyhost.com&login=fail&user=administrator'})
print r.status_code
print r.headers
print r.content
softwarePackages = requests.post("https://myhost.com/context-root/rest/softwarePackage/list", verify=False, data={'offset': 1, 'limit': 10, 'sortBy': 'importDate', 'ascending': 'false', 'platform': 'null'})
print softwarePackages.status_code
print softwarePackages.headers
print softwarePackages.content
Answer: Use [`Session` object](http://docs.python-
requests.org/en/latest/user/advanced/#session-objects):
import requests
import requests
s = requests.Session()
r = s.post("https://myhost.com/login", verify=False, data={...})
softwarePackages = s.post(
"https://myhost.com/context-root/rest/softwarePackage/list",
verify=False, data={...}
)
print softwarePackages.status_code
print softwarePackages.headers
print softwarePackages.content
> The Session object allows you to persist certain parameters across requests.
> It also persists cookies across all requests made from the Session instance.
|
Tkinter entry widget lags while typing. How to update typed text in real time?
Question: Using python3. I'm new to tkinter writing a program with a GUI that takes some
input parameters and does some data processing, so it needs entry boxes where
I can type numbers in.
I cannot for the life of me figure out how to get the entry boxes to stop
lagging, i.e: when a box is clicked on and typed into, the changes made to the
text in that entry box don't appear until I click on another button or text
box in the window. Functionally, the program still works like this but it's
irritating not being able to see what I'm typing and others will eventually
use this software.
I've gotten halfway to fixing the problem by putting in event bindings so that
key presses trigger an update of the idle tasks. The text now updates while
typing, but it's "one letter slow" (a typed letter appears only after the next
letter is typed) and this is still not ideal.
Help?
MWE:
from tkinter import *
###Window: 'top'
top = Tk() #make window
top.geometry("670x360") #window size
top.wm_title("Test program for TKinter")#window title
#window and label background colour
bgcol='light sea green'
top.configure(background=bgcol) #set colour
#events to refresh window
def keypress(event):
print('key pressed')
#update all idle widgets (remove text box lag)
top.update_idletasks()
def mouseentry(event):
print('mouse entered text box')
#update all idle widgets (remove text box lag)
top.update_idletasks()
##text entry box
Label(top,background=bgcol, text="").pack() #spacing label
v = StringVar()
e=Entry(top, width=50, textvariable=v)#,height=1)
e.pack()
Label(top,background=bgcol, text="").pack() #spacing label
v.set("a default value")
s = e.get()
e.bind("<Key>",keypress)
e.bind("<Enter>",mouseentry)
#Label displaying text box contents (not working right now, not important)
Label(top,background=bgcol, textvariable=s).pack() #text display label
#make buttons appear on start
top.update()
top.mainloop()
How do I update the entry widget as it is typed? Is there something really
simple that I'm overlooking?
Answer: Answer to own question:
Mainloop wasn't running in the background (or something) of my python install,
for whatever reason, whether run via Anaconda or via the terminal.
Simple reinstall of Anaconda IDE with python3.4 fixed all my issues.
|
Find.Execute not working with package Win32com
Question: I got a problem that I really can't understand with a Python script I found on
Stackoverflow 2 weeks ago and which worked perfectly until yesterday (with no
changes at all !)
I got a document where I want to find a list of words and replace them with
other words. Here is my code :
import win32com.client
word = win32com.client.DispatchEx("Word.Application")
word.Visible = True
word.DisplayAlerts = False
word.Documents.Open(path)
FromTo = {"<#TITLE#>":"The title I want", "<#COMPANY#>":"My Company"}
for From in FromTo.keys():
word.Selection.Find.Text = From
word.Selection.Find.Replacement.Text = FromTo[From]
word.Selection.Find.Execute(Replace=2, Forward=True)
word.ActiveDocument.SaveAs(path)
The thing is that the document is opened, the text to find is selected
properly, but nothing happens as the code comes to line
`word.Selection.Find.Execute(Replace=2, Forward=True)`. The document is
normally saved after that, and I got no error message.
Does someone have an idea about why this code doesn't work ? It's quite weird
that the same code worked two weeks ago and doesn't make anything right now.
Thanks for helping me !
Answer: I know this is old, but I was having the same issue and found that if I change
gen_py to xxgen_py in site-packages\win32com (essentially making it unusable)
I no longer have this issue. I'm not sure what is going on, but this was the
only way I could get fin.execute to actually replace the words and not just
highlight.
edit: using the other replacement method in the previous answer worked for me,
keeping gen_py folder.
|
Print lines with constraint in Python
Question: Suppose we have the following text file with column `a` and column `b`:
D000001 T109
D000001 T195
D000002 T115
D000002 T131
D000003 T073
D000004 T170
I wonder how to produce the following structure:
D000001 T109 T195
D000002 T115 T131
D000003 T073
D000004 T170
Pasted below is initial skeleton in Python.
from __future__ import print_function
with open('descr2semtype_short.txt') as f:
for line in f:
line = line.rstrip()
a, b = line.split()
print(a + ' ' + b)
Answer: You can use `itertools.groupby`:
import itertools, operator
with open('descr2semtype_short.txt') as f:
for key, items in itertools.groupby(
(line.rstrip().split(None,1) for line in f),
operator.itemgetter(0)):
print(key, ' '.join(item[1] for item in items))
which gives the desired output:
D000001 T109 T195
D000002 T115 T131
D000003 T073
D000004 T170
|
Python datetime.strptime - parse complicated string
Question: I want to make datetime from following string '2015-06-29T11:55:30.000000Z'.
I tried:
import datetime
print datetime.datetime.strptime("2015-06-29T11:55:30.000000Z", "%y-%m-%dT%H:%M:%S.000000Z")
and I obtained following error:
Traceback (most recent call last):
File "x1.py", line 5, in <module>
print datetime.datetime.strptime(date, "%y-%m-%dT%H:%M:%S.000000Z")
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '2015-06-29T11:55:30.000000Z' does not match format '%y-%m-%dT%H:%M:%S.000000Z'
What I am doing wrong? How to parse it?
Answer: Capitalize `%Y`:
import datetime as DT
DT.datetime.strptime("2015-06-29T11:55:30.000000Z", "%Y-%m-%dT%H:%M:%S.000000Z")
# datetime.datetime(2015, 6, 29, 11, 55, 30)
`%y` matches 2-digit years -- [years without century as a decimal number
year](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-
behavior). `%Y` matches 4-digit years.
|
UnicodeEncodeError with nginx and django
Question: I've tried [this SO
answer](http://stackoverflow.com/questions/3715865/unicodeencodeerror-ascii-
codec-cant-encode-character), [this doc is
inapplicable](https://docs.djangoproject.com/en/1.4/howto/deployment/modpython/#if-
you-get-a-unicodeencodeerror) as I'm running nginx, I've added `charset
utf-8;` to my nginx config and I'm still getting this error.
Summarised traceback is here:
UnicodeEncodeError at /
'ascii' codec can't encode character u'\xe1' in position 69: ordinal not in range(128)
Request Method: GET
Request URL: http://django/
Django Version: 1.4.20
Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode character u'\xe1' in position 69: ordinal not in range(128)
Exception Location: /opt/envs/venv/lib/python2.7/genericpath.py in getmtime, line 54
Unicode error hint
The string that could not be encoded/decoded was: choacán.jpg
Answer: I think this error is not about nginx. It's on the file creation step. Python
uses system locale when saving files.
Check your system locale:
$ python manage.py shell
> import os
> print os.popen("locale").read()
If it's incorrect you should set system locale.
But filenames like this can cause any kind of troubles for users. Please think
about defining custom file storage for models.FileField and generating random
file name for every file - it's good practice.
|
Python Regex split text file into sentences and append to a list
Question: I've been trying to solve this problem without using any external modules, but
only inbuilt python Regex. I've got this so far. The file i'm reading is a
.txt file
import re
def GetText(filename):
print('Opening file...')
text_file= open(filename,'r')
lines = text_file.readlines() #each line is appended to a list
with text_file:
one_string= text_file.read().replace('\n', '')
print(one_string)
Answer: Instead of reading the whole file a line at atime why not read it all in one
go and then split based on full stops (periods) in order to get sentences...
ie:
text_file= open(filename,'r')
data=text_file.read()
listOfSentences = data.split(".")
|
py2exe and Tableau Python API
Question: First of all, please excuse me if I'm using some of the terminology
incorrectly (accountant by trade ...)
I'm writing a piece of code that I was planning to pack as .exe product.
I've already included number of standard libraries (xlrd, csv, math, operator,
os, shutil, time, datetime, and xlwings). Unfortunately, when I've added
'dataextract' library my program stopped working.
dataextract is an API written specifically for software called Tableau (one of
the leading BI solutions on the market). Also Tableau website says it does not
provide any maintenance support for it at the moment.
I've tested it on very basic setup:
from xlwings import Workbook, Sheet, Range
Workbook.set_mock_caller(r'X:\JAC Reporting\Tables\Pawel\Development\_DevXL\Test1.xlsx')
f = Workbook.caller()
s = raw_input('Type in anything: ')
Range(1, (2, 1)).value = s
This works perfectly fine. After adding:
import dataextract as tde
The Console (black box) will only flash on the screen and nothing happens.
Questions:
1. Does library (in this case 'dataextract') has to meet certain criteria to be compatible with py2exe?
2. As Tableau does not maintain the original code, does it mean I won't be able to pack it into .exe using py2exe?
Finally: I'm using 'dataextract' for almost 2 years now and as long as you
will run the program through .py file it works like a charm :) I just decided
to take it one step further.
Any comments/input would be greatly appreciated.
EDIT: Not sure does it help or not, but when I tried to run the same script
using cx_Freeze compiler got below error:

Answer: First of all massive thanks to @Andris as he pointed me at the correct
direction.
It turned out dataextrac library dlls are not automatically copied while
compiler is running. Therefore you need to copy them from 'site-
package/dataextrac/bin' into 'dist' folder.
Also from 12 dlls you only need 9 of them (I tried running exe file for each
of them). One you don't need are: icin44.dll, msvcp100.dll and msvcr100.dll.
To be on the safe side I will be coping them anyway though.
Hope this post will be any help to otheres :)
|
Django Admin panel not working with https
Question: I have a Django project which I just deployed using Apache and mod_wsgi, which
seemed to be working perfectly. I then changed the Apache config file to allow
HTTPS and now my admin site is not working (though the regular site does work
with both http and https).
First, if I go to <http://www.example.com/admin> or
<https://www.example.com/admin>, I get "Server Error (500)". There is nothing
listed in my Apache error log but I get the following line in
other_vhosts_access.log:
With HTTPS:
"GET /admin/login/?next=/admin/ HTTP/1.1" 500 553 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
With HTTP:
"GET /admin/login/?next=/admin/ HTTP/1.1" 500 300 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
Second, if I login to www.example.com using my admin username and password AND
THEN go to www.example.com/admin I get the standard admin panel (if I use
HTTP) or I get the admin panel minus any CSS (when I use HTTPS).
Here is my current Apache config file (EDITED to add missing /static alias):
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName www.example.com
ServerAlias www.example.com
DocumentRoot /srv/www/www.example.com
Alias /static /srv/www/www.example.com/static
<Directory /srv/www/www.example.com/static>
Order allow,deny
Allow from all
</Directory>
<Directory /srv/www/www.example.com/my_app>
<Files wsgi.py>
Allow from all
</Files>
</Directory>
WSGIDaemonProcess my_app python-path=/srv/www/bcsurvey.wwbp.org:/srv/www/www.example.com/virtenv/lib/python2.7/site-packages
WSGIProcessGroup my_app
WSGIScriptAlias / /srv/www/www.example.com/my_app/wsgi.py
</VirtualHost>
NameVirtualHost *:443
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/apache2/sslkey/mykey.crt
SSLCertificateKeyFile /etc/apache2/sslkey/mykey.crt
ServerAdmin webmaster@localhost
ServerName www.example.com
ServerAlias www.example.com
DocumentRoot /srv/www/www.example.com
WSGIProcessGroup my_app
WSGIScriptAlias / /srv/www/www.example.com/my_app/wsgi.py
Alias /static /srv/www/www.example.com/static
<Directory /srv/www/www.example.com/static>
Order allow,deny
Allow from all
</Directory>
<Directory /srv/www/www.example.com/my_app>
<Files wsgi.py>
Allow from all
</Files>
</Directory>
</VirtualHost>
Here is my settings.py file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATIC_ROOT = '/srv/www/www.example.com'
MEDIA_PATH = os.path.join(BASE_DIR, 'media')
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'mykey'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['www.example.com']
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'survey',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'my_app.urls'
WSGI_APPLICATION = 'my_app.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = (
STATIC_PATH,
)
MEDIA_URL = '/media/'
MEDIAFILES_DIRS = (
MEDIA_PATH,
)
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.email.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'myemailpassword'
DEFAULT_FROM_EMAIL = '[email protected]'
DEFAULT_TO_EMAIL = 'to email'
Also, I am using Django v. 1.7.
Answer: **Edit:** Real error was the missing **SITE_ID** setting. See comments for out
little debug session...
_Original answer:_ You're missing the /static Alias in your https config.
Are the static assets requested by https?
Additionally, you're missing the WSGIDaemonProcess statement in your https
config.
|
SublimeREPL on Sublime Text 3 not importing Python 2.7 modules
Question: I have been trying to configure SublimeText 3 to run SublimeREPL, setting
everything so it runs as IDLE, or PyCharm IDE, but, after trying different
options I checked in SO, it keeps returning:
>>> import pandas
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named pandas
>>> import os
>>> os.environ['PYTHONPATH']
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'PYTHONPATH'
I have tried editing the SublimeREPL.sublime-settings file with the default
extend path file you can see at the FAQ site of SublimeREPL, but still does
not work.
Does anyone know how this could be solved?
Answer: I don't know if this is the problem for you, but I was getting the exact same
error and learned that by opening sublime text from the command line (e.g.
'subl .' to open the directory, once you have that shortcut set up) you get
one PATH- and if you open sublime text from Spotlight Search you get another
PATH. Try opening sublime text from the command line once you've confirmed you
can import pandas in an interactive command line session and hopefully it will
work.
|
Conditional passing of arguments to methods in python
Question: I have many possible arguments from argparse that I want to pass to a
function. If the variable hasn't been set, I want the method to use its
default variable. However, handling which arguments have been set and which
haven't is tedious:
import argparse
def my_func(a = 1, b = 2):
return a+b
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Get the numeric values.')
parser.add_argument('-a', type=int)
parser.add_argument('-b', type=int)
args = parser.parse_args()
if not args.a is None and not args.b is None:
result = my_func(a = args.a, b = args.b)
elif not args.a is None and args.b is None:
result = my_func(a = args.a)
elif not args.b is None and args.a is None:
result = my_func(b = args.b)
else:
result = my_func()
It seems like I should be able to do something like this:
result = my_func(a = args.a if not args.a is None, b = args.b if not args.b is None)
But this gives a syntax error on the comma.
I could set default values in the argparser, but I want to use the defaults
set in the method definition.
Answer: Use a dictionary with the kwargs unpacking syntax.
args = parser.parse_args()
result = my_func(**vars(args))
**Edit**
Use the `SUPPRESS` argument to ArgumentParser to remove empty values:
parser = argparse.ArgumentParser(description='Get the numeric values.',
argument_default=argparse.SUPPRESS)
|
Making a successful Bluetooth Connection to RPi
Question: I have a RPi and a normal Debian on my pc, both using the Bluetooth Python
module to communicate. Both have some Bluetooth USB dongle in them. I can use
the pc as server and the RPi as client, this connection works very well.
However I'm not able to do it vice versa, I checked my `rfcomm.conf` and
`main.conf`, but both seem to be ok. Any other pitfalls?
* * *
#Server.py
import bluetooth
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print "Accepted connection from ",address
data = client_sock.recv(1024)
print "received [%s]" % data
client_sock.close()
server_sock.close()
* * *
#Client.py
import bluetooth
bd_addr = #myspecificmacaddress
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("hello!!")
sock.close()
* * *
So to be more precise: Running `Client.py` on RPi and `Server.py` on pc works
fine, doing vice versa, obviously with corrected MAC, simply says:
`bluetooth.btcommon.BluetoothError: (112, 'Host is down')`
Answer: Turned out that my config files weren't that well. (it must had to do
something with config files)
`/etc/bluetooth/main.conf` has a class section.
`/var/lib/bluetooth/XX:XX:XX:XX:XX:XX/config` has a class section, too.
I do not know why, I do not know how or what is actually happening, as you are
not able to find anything about this on the internet, but setting _both_ to
`0x400100` fixed it. I don't know if they just have to match or if it's some
special thing I came up by fortune, but it works and I dont really want to
possibly break it again.
Maybe someone with more knowledge about this is willing to improve my answer
here.
|
Python to Javascript JSON objects (Flask)
Question: I am trying to create a simple Flask app where an array of integers is
generated on the server and sent to the client. I want to view the array of
integers in the console. Here is some sample (working) code in app.py:
from flask import Flask, render_template, request, url_for
import random, json
app = Flask(__name__)
@app.route('/', methods=['GET'])
def form():
json_helper = {}
json_helper['randoms'] = [random.random() for _ in range(40)]
json_object = json.dumps(json_helper)
return render_template('sim0625.html', s_data=json_object)
if __name__ == '__main__':
app.run(debug=True)
And here is a snippet of the Javascript frontend:
<script>
var data_xyz = {{ s_data|tojson }};
var JSONObject = JSON.parse({{data_xyz}});
console.log(JSONObject.randoms);
</script>
Unfortunately, none of the javascript works on my webpage, and the error
message shown is "Uncaught SyntaxError: Unexpected token u".
Can someone please explain how to fix this? Thanks. My guess is the JSON
objects are becoming strings.
Note: The code from the front-end was adapted from this SO question:
[Extracting data from json object in jQuery or
JS](http://stackoverflow.com/questions/10926965/extracting-data-from-json-
object-in-jquery-or-js)
Answer: You're sending your JSON to the template through the variable `s_data`.
In the template, you're rendering that variable into a _JavaScript_ variable
called `data_xyz`. In the next line, you attempt to reference a Jinja variable
instead of a JavaScript variable:
var JSONObject = JSON.parse({{data_xyz}});
Change that to:
var JSONObject = JSON.parse(data_xyz);
|
How to programmatically count the number of files in an archive using python
Question: In the program I maintain it is done as in:
# count the files in the archive
length = 0
command = ur'"%s" l -slt "%s"' % (u'path/to/7z.exe', srcFile)
ins, err = Popen(command, stdout=PIPE, stdin=PIPE,
startupinfo=startupinfo).communicate()
ins = StringIO.StringIO(ins)
for line in ins: length += 1
ins.close()
1. Is it really the only way ? I can't seem to find [any other command](http://sevenzip.osdn.jp/chm/cmdline/commands/) but it seems a bit odd that I can't just ask for the number of files
2. What about error checking ? Would it be enough to modify this to:
proc = Popen(command, stdout=PIPE, stdin=PIPE,
startupinfo=startupinfo)
out = proc.stdout
# ... count
returncode = proc.wait()
if returncode:
raise Exception(u'Failed reading number of files from ' + srcFile)
or should I actually parse the output of Popen ?
EDIT: interested in 7z, rar, zip archives (that are supported by 7z.exe) - but
7z and zip would be enough for starters
Answer: To count the number of archive members in a zip archive in Python:
#!/usr/bin/env python
import sys
from contextlib import closing
from zipfile import ZipFile
with closing(ZipFile(sys.argv[1])) as archive:
count = len(archive.infolist())
print(count)
It may use `zlib`, `bz2`, `lzma` modules if available, to decompress the
archive.
* * *
To count the number of regular files in a tar archive:
#!/usr/bin/env python
import sys
import tarfile
with tarfile.open(sys.argv[1]) as archive:
count = sum(1 for member in archive if member.isreg())
print(count)
It may support `gzip`, `bz2` and `lzma` compression depending on version of
Python.
You could find a 3rd-party module that would provide a similar functionality
for 7z archives.
* * *
To get the number of files in an archive using `7z` utility:
import os
import subprocess
def count_files_7z(archive):
s = subprocess.check_output(["7z", "l", archive], env=dict(os.environ, LC_ALL="C"))
return int(re.search(br'(\d+)\s+files,\s+\d+\s+folders$', s).group(1))
Here's version that may use less memory if there are many files in the
archive:
import os
import re
from subprocess import Popen, PIPE, CalledProcessError
def count_files_7z(archive):
command = ["7z", "l", archive]
p = Popen(command, stdout=PIPE, bufsize=1, env=dict(os.environ, LC_ALL="C"))
with p.stdout:
for line in p.stdout:
if line.startswith(b'Error:'): # found error
error = line + b"".join(p.stdout)
raise CalledProcessError(p.wait(), command, error)
returncode = p.wait()
assert returncode == 0
return int(re.search(br'(\d+)\s+files,\s+\d+\s+folders', line).group(1))
Example:
import sys
try:
print(count_files_7z(sys.argv[1]))
except CalledProcessError as e:
getattr(sys.stderr, 'buffer', sys.stderr).write(e.output)
sys.exit(e.returncode)
* * *
To count the number of lines in the output of a generic subprocess:
from functools import partial
from subprocess import Popen, PIPE, CalledProcessError
p = Popen(command, stdout=PIPE, bufsize=-1)
with p.stdout:
read_chunk = partial(p.stdout.read, 1 << 15)
count = sum(chunk.count(b'\n') for chunk in iter(read_chunk, b''))
if p.wait() != 0:
raise CalledProcessError(p.returncode, command)
print(count)
It supports unlimited output.
* * *
> Could you explain why buffsize=-1 (as opposed to buffsize=1 in your previous
> answer: stackoverflow.com/a/30984882/281545)
`bufsize=-1` means use the default I/O buffer size instead of `bufsize=0`
(unbuffered) on Python 2. It is a performance boost on Python 2. It is default
on the recent Python 3 versions. You might get a short read (lose data) if on
some earlier Python 3 versions where `bufsize` is not changed to `bufsize=-1`.
This answer reads in chunks and therefore the stream is fully buffered for
efficiency. [The solution you've
linked](http://stackoverflow.com/a/30984882/281545) is line-oriented.
`bufsize=1` means "line buffered". There is minimal difference from
`bufsize=-1` otherwise.
> and also what the read_chunk = partial(p.stdout.read, 1 << 15) buys us ?
It is equivalent to `read_chunk = lambda: p.stdout.read(1<<15)` but provides
more introspection in general. It is used to [implement `wc -l` in Python
efficiently](http://stackoverflow.com/questions/9371238/why-is-reading-lines-
from-stdin-much-slower-in-c-than-python#comment11966378_9371238).
|
python - How to count and take averages on a tuple with Paired values
Question: I am new to python. Can you please help me with this? I have a tuple lets say
`(100, (10.0, 20.0, 30.0))`. I need to write a function which will take this
as an input and return `(100, (3, 20.0))` where `3` is the value count and
`20` is the value of average.
Answer: Have you tried something like this with numpy:
import numpy
def myfunction(mytuple):
myresult=(mytuple[0],(len(mytuple[1]),numpy.mean(mytuple[1])))
return myresult
|
Python converting text file to all caps
Question: I'm new to python, and I'm trying to figure out how to write a program that
prompts the user for the name of a text file, converts the contents of the
text file to all caps, and then saves it as a new file.
Answer:
import os
def main():
fp = raw_input('Filename: ')
if fp and os.path.isfile(fp):
with open(fp, 'r') as f:
txt = f.read()
newfp = '{0}_upper{1}'.format(*os.path.splitext(fp))
with open(newfp, 'w') as f:
f.write(txt.upper())
if __name__ == '__main__':
main()
|
Python Port Scanner says all ports are closed
Question: I'm decently skilled in python programming and i'm trying to make a port
scanner without using any third party libraries. Below is the code I've
written so far but the problem is that when i scan my laptop's IP address, it
says that all the ports are closed. Is there something wrong with my code or
are all the ports actually closed(if so, why?). Any help will be much
appreciated, thanks.
from socket import *
class scanner():
def __init__(self, ip):
self.ip = ip
self.scan()
def scan(self):
print("Starting scan on host: %s "%(self.ip))
for i in range(0, 10000):
s = socket(AF_INET, SOCK_STREAM)
try:
s.connect((ip, i))
print('Port %d: OPEN' % (i))
s.close()
except:
print('Port %d: CLOSED' % (i))
s.close()
ip = input("Input IP address to scan: ")
scanner(ip)
Answer: You need to connect to the ip you're passing into the constructor: instead of:
s.connect((ip, i))
try:
s.connect((self.ip, i))
Hope that helps!
|
Bad file descriptor error with flask-mail
Question: I'm using flask-mail to send the user an email with their new password. I keep
getting IOError bad file descriptor when I run the code
app.config.update(
DEBUG=True,
#EMAIL SETTINGS
MAIL_SERVER='smtp.gmail.com',
MAIL_PORT=465,
MAIL_USE_SSL=True,
MAIL_USE_TLS= False,
MAIL_USERNAME = '[email protected]',
MAIL_PASSWORD = 'mypass'
)
mail = Mail(app)
@app.route('/api/account', methods= ['POST'])
def login():
e= request.json ['email']
u= request.json ['user']
p= request.json ['pass']
msg= Message("Your password", sender= '[email protected]',recipients = ['destinationemail'])
msg.body= 'Your password is ' + hashedp
#msg.html ='<b> password </b>'
mail.send(msg)
return 'Your new password has been sent through email'
Does this have something to do with sockets and connection? I can post the
full traceback if needed
EDIT full traceback:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\mpelixp\Documents\joanna\app2api.py", line 95, in login
mail.send(msg)
File "C:\Python27\lib\site-packages\flask_mail.py", line 491, in send
with self.connect() as connection:
File "C:\Python27\lib\site-packages\flask_mail.py", line 144, in __enter__
self.host = self.configure_host()
File "C:\Python27\lib\site-packages\flask_mail.py", line 165, in configure_host
host.login(self.mail.username, self.mail.password)
File "C:\Python27\lib\smtplib.py", line 582, in login
self.ehlo_or_helo_if_needed()
File "C:\Python27\lib\smtplib.py", line 542, in ehlo_or_helo_if_needed
if not (200 <= self.ehlo()[0] <= 299):
File "C:\Python27\lib\smtplib.py", line 414, in ehlo
(code, msg) = self.getreply()
File "C:\Python27\lib\smtplib.py", line 370, in getreply
print>>stderr, 'reply:', repr(line)
IOError: [Errno 9] Bad file descriptor
Answer: If it doesn't work you can always use `yagmail`:
import yagmail
yag = yagmail.SMTP(MAIL_USERNAME, MAIL_PASSWORD)
yag.send(to = e, contents = 'Your password is ' + hashedp)
First install it with `pip install yagmail` (or `pip3` for python 3).
It has a lot of functionality, including easily sending HTML emails (with
fallback), attaching by pointing to a file and passwordless scripts.
See more on [github](https://github.com/kootenpv/yagmail).
|
Tkinter: How to make a button center itself?
Question: I'm making a program in Python and I want to go with a layout that is a bunch
of buttons in the center. How do I make a button center itself using pack()?
Answer: If this can't resolve your problem
button.pack(side=TOP)
You'll need to use the method
button.grid(row=1,col=0)
the values of `row=1,col=0` depend of the position of the other widget in your
window
or you can use `.place(relx=0.5, rely=0.5, anchor=CENTER)`
button.place(relx=0.5, rely=0.5, anchor=CENTER)
Example using `.place()`:
from tkinter import * # Use this if use python 3.xx
#from Tkinter import * # Use this if use python 2.xx
a = Button(text="Center Button")
b = Button(text="Top Left Button")
c = Button(text="Bottom Right Button")
a.place(relx=0.5, rely=0.5, anchor=CENTER)
b.place(relx=0.0, rely=0.0, anchor=NW)
c.place(relx=1.0, rely=1.0, anchor=SE)
mainloop

|
Remove 1 version of Python in Ubuntu
Question: So apparently I have 2 Pythons (same version) installed in different
folders...one is in `/usr/bin/` and the other one is in `/usr/local/bin` but
the one the shell uses when I type in `python` is the one in `/usr/local/bin`.
I'd like to use the `/usr/bin/` version because is the one that works with
many imports I've been dealing with such as `numpy`,`matplotlib` and
`Tkinter`.
I've tried using `pyenv` but with this I cannot run `Tkinter` because
`Tkinter` is installed only for the `/usr/bin/` version.
* Is there a safe way I can delete/uninstall one of those versions without breaking my whole Ubuntu?
* Is there a way to tell the shell to use the `/usr/bin/` version of Python?
* Is there a way I can install `python-tk` for any `envpy` version? Something like `sudo apt-get install python-tk in-desired-folders` or similar?
Answer for any of those 3 questions would solve my problem, I think.
Thank you all in advice!
Answer: If these two Python installations are identical (same Python version), there
is no reason you can't use the Python packages installed for one version with
the other. You'd just have to adjust your `PYTHONPATH`:
export PYTHONPATH=/usr/lib/python2.7/site-packages
or variants thereof, depending where exactly the standard (system) Python has
installed its packages.
You can find the latter by starting that Python explicitly, and looking at
`sys.path`. On my Ubuntu system, for example:
> /usr/bin/python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/evert/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
and my `PYTHONPATH` should be set to
export PYTHONPATH=/usr/lib/python2.7/dist-packages
instead.
* * *
Alternatively, and perhaps even easier, just create an alias to the Python you
want to use (just don't name the alias `python`; it will sow lots of
confusion):
alias py2=/usr/bin/python
and use that instead.
In either case, no need to remove anything in `/usr/local/` (or even putting
`/usr/bin/` at the front of your `PATH`); you just move the /usr/local
directory/Python out of your way.
|
Python unit test mock, get mocked function's input arguments
Question: I want a unit test to assert that a variable `action` within a function is
getting set to its expected value, the only time this variable is used is when
it is passed in a call to a library.
Class Monolith(object):
def foo(self, raw_event):
action = # ... Parse Event
# Middle of function
lib.event.Event(METADATA, action)
# Continue on to use the build event.
My thought was that I could mock `lib.event.Event`, and get its input
arguments and assert they are of specific value.
>Is this not how mocks work? The mock documentation frustrates me with its
inconsistency, half-examples, and plethora of examples that are not related to
what I want to do.
Answer: You could use patch decorator and then call **assert_called_with** to that
mocked object like this:
If you have this structure:
example.py
tests.py
lib/__init__.py
lib/event.py
And the content of **example.py** is:
import lib
METADATA = 'metadata_example'
class Monolith(object):
def foo(self, raw_event):
action = 'action_example' # ... Parse Event
# Middle of function
lib.event.Event(METADATA, action)
# Continue on to use the build event.
And the content of **lib/event.py** is:
class Event(object):
def __init__(self, metadata, action):
pass
The code of **tests.py** should be like:
import mock
import unittest
from lib.event import Event
from example import Monolith
class TestExample(unittest.TestCase):
@mock.patch('lib.event.Event')
def test_example1(self, event_mocked):
# Setup
m = Monolith()
# Exercise
m.foo('raw_event')
# Verify
event_mocked.assert_called_with('metadata_example', 'action_example')
|
how to use a variable in requests library of python
Question: I'm trying to make a script which reads crunchyroll's rss and visits the LINK
in the latest upload and downloads subs from it.. the process goes like : 1.)
Read The latest episode link from RSS. 2.) Go to the link 3.) In the source
code, look for text "ssid". 4.) Get the 6 characters of the ssid. 5.) Then
append those characters at the end of this like
"[http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=](http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=)"
and save the xml page.
My script works half way...
My Code:-
import feedparser
import webbrowser
import os
import subprocess
import re
import urllib
import urllib2
from urllib2 import urlopen
from bs4 import BeautifulSoup
import requests
import cookielib
feed = feedparser.parse('http://www.crunchyroll.com/rss/anime') #checks the RSS
url = feed['entries'][0]['link'] + '?p720=1' # get's the link from latest release and appends some character for the 720p resolution of the link.
# Now, here, I'm writing this URL to a text file and then read from the text file
file = open("newfile.txt", "w")
file.write(url)
file.close()
file = open('newfile.txt', 'r')
#print file.read()
lobo = file.read()
print lobo
# Now, I put the URL that is being read from file in requests to go to the link. Everything works fine till here.
r = requests.get(lobo)
soup = BeautifulSoup(r.text)
print soup.title
webbrowser.open_new_tab(lobo)
subtitles = soup.findAll('span',{'class':'showmedia-subtitle-text'})
for ssid in subtitles:
x = ssid.find_all('a', limit=1)
for a in x:
print a['href'][-6:]
xmlLink = 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + a['href'][-6:]
#webbrowser.open_new_tab(xmlLink)
print xmlLink
Now, I get error that 'a' in this xmlLink is not defined.
But, there's a twist to it... if I put the direct http link in "r =
requests.get(lobo)" .. everything works like it is supposed to.But, if I use
this variable.. it's not working.
Any help would be appreciated.Thank You
Answer: It looks like the `a` variable is defined inside of the `for` loop but the
`xmlLink` variable is not. Try indenting the `xmlLink` line in to match the
indentation level of the `for` loop. For example:
for a in x:
print a['href'][-6:]
xmlLink = 'http://www.crunchyroll.com/xml/?req=RpcApiSubtitle_GetXml&subtitle_script_id=' + a['href'][-6:]
#webbrowser.open_new_tab(xmlLink)
print xmlLink
|
Stopping a timer with a specific code
Question: I'm trying to make a Bomb timer than can be stopped at any given moment using
a specific code. which is 7355608
I've tried doing this but I fail at it, also please keep in mind I'm
relatively new to python.
Also, thanks in advance.
import time
def countdown():
for n in range(45, 0, -1):
print n
time.sleep(1)
code = int(raw_input("Enter code:"))
if code == passcode:
break
countdown()
passcode = 7355608
P.S: I know the code is really bad, because I'm new to python.
Answer: You need to tell the program what "passcode" is before the countdown() method
definition, or else python doesn't know what "passcode" means. Just move the
statement "passcode = 7355608" to above the method block and it should work!
|
Why do I keep getting a syntax error message (in Python) when using append?
Question: The syntax error is at line 9.
# -*- coding: UTF-8 -*-
import math
x = []
y = []
n = raw_input('How many points: ')
number = n
while n > 0:
x.append(input('enter x: ')
y.append(input('enter y: ')
n = n - 1
d = []
n = number
while n > 0:
d.append(math.sqrt((x[n-1] - x[n-2])**2 + (y[n-1] - y[n-2]**2
n = n - 1
d.append(math.sqrt((x[number-1] - x[0])**2 + (y[number-1] - y[0]**2
p = 0
n = number
while n > 0:
p = p + d[n-1]
n = n - 1
print(‘Perimeter =’)
print(p)
input(‘Press 0 and then enter to continue:’)
What am I doing wrong? Also, I am only a beginner in Python, so an easy to
understand explanation would be helpful.
This is what is popping up in my terminal:
File "prg1.py", line 9
y.append(input('enter y: ')
^
SyntaxError: invalid syntax
Answer: There are so many errors of your code.
1. as a function, input and append both need (), so line 8 and 9 should be
x.append(input('enter x: '))
y.append(input('enter y: '))
2. the type of
raw_input('How many points: ')
is string, if you need add 1 to n, you should convert it to int using int()
function.
3. append(),sqrt() also missing ')' .
|
LSTM with 12 input and output nodes with no embedding
Question: all I need is a RNN LSTM with 12 input nodes, 12 output nodes and have ability
to tweak hidden layers (their number and size).
The elements of input and output vectors can be real numbers or integers (I
have integers on input). Is it necessary to use one hot encoding here (because
it would be unusable with so many combinations)? I thought that this layer is
redundant, since my inputs are already vectors.
I couldn't build this neural network with Python (Lasagne, Block, Keras...)
nor Torch.
The closest I've got so far is with Pybrain, but this package is in
"maintance" mode (only bug fixes), is terribly slow (it's not built on Theano)
and supports only one LSTM layer, which is insufficient. But at least it does
what I want - it takes one vector of 12 numbers and returns another vector of
12 numbers.
Here is an example using pybrain:
# Preparing data
from pybrain.datasets import SequentialDataSet
from itertools import cycle
sp = 4000
data = np.random.randint(1,100,(5000,12))
def splt_seq(data):
sq = SequentialDataSet(12, 12)
for sample, next_sample in zip(data, cycle(data[1:])):
sq.addSample(sample, next_sample)
return(sq)
train = splt_seq(data[:sp])
test = splt_seq(data[sp:sp+200])
# Building network and training
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules import LSTMLayer
net = buildNetwork(12, 100, 12,
hiddenclass=LSTMLayer, outputbias=False, recurrent=True)
from pybrain.supervised import RPropMinusTrainer
from sys import stdout
trainer = RPropMinusTrainer(net, dataset=train)
train_errors = [] # save errors for plotting later
EPOCHS_PER_CYCLE = 5
CYCLES = 100
EPOCHS = EPOCHS_PER_CYCLE * CYCLES
for i in range(CYCLES):
trainer.trainEpochs(EPOCHS_PER_CYCLE)
train_errors.append(trainer.testOnData())
epoch = (i+1) * EPOCHS_PER_CYCLE
print("\r epoch {}/{}".format(epoch, EPOCHS), end="")
stdout.flush()
print()
print("final error =", train_errors[-1])
net.activate(X_test.getSample()[0])
With keras I haven't got to far, as can be seen
[here](https://groups.google.com/forum/#!topic/keras-users/-L4k2VQ0GXk)
Answer: It depends. You did not specify the details of your input, other than its
length and type. Are the elements of your input vector discrete or continuous?
If they are discrete, you must one-hot encode your vector. Else you could feed
your data directly to your RNN-LSTM.
Difference between discrete and continuous:
Suppose your vector contains information regarding 12 cards that were randomly
picked from a deck of cards. You might have indexed your cards from 0 to 51
(52 cards in a deck) and your input vector would look like this:
[3,4,17,50,20,10,11,36,5,0,23,49]
Now you have a problem, the indices of each card do not represent any
quantitative measure of the cards (card 50 is not 5 times more 'something'
than card 10). So you have to one hot encode the vectors, so that the cards
would dwell in a larger space, equidistant from each other:
[e(3,52),e(4,52),e(17,52)......e(23,52)]
If your input contains continuous data like weather information,(each of the
12 elements being different factors like temperature,wind,humidity, etc), one
hot encoding it would not make any sense. Just input the vector to your RNN-
LSTM as is.
As you have mentioned that the input could also be real numbers, its more
probable that your input is continuous and need not be one hot encoded. Hope
that helps!
|
HtmlResponse from Scrapy doesn't retrieve the data from URL
Question: These are the code run in Ipython.
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
response = HtmlResponse(url='https://en.wikipedia.org/wiki/Pan_American_Games')
datas = Selector(response=response).xpath('//div[@class="thumb tleft"]')
When I execute `response` I got `<200
https://en.wikipedia.org/wiki/Pan_American_Games>` But when I execute
`reponse.body` I got `''` (NULL)
It seems like `HtmlResponse` doesn't retrieve any HTML's info for this page.
Does any know how to fix this?
FYI, if I ran `$ scrapy shell
https://en.wikipedia.org/wiki/Pan_American_Games` in command prompt then
response won't be NULL. I don't want to do the`scrapy shell url`way since I
will be running for loop through the list of URL.
Thanks
Answer: The issue is that you are not writting a spider here. `HtmlResponse` doesn't
do any data retrieving from the internet so to say. What you have is only a
response object with only the url attribute you've provided.
Here's is a great official depiction of architecture of scrapy:
<http://doc.scrapy.org/en/latest/topics/architecture.html?highlight=scrapy%20architecture>
However if you do want to use scrapy features like selectors without scrapy
spiders you can use `requests` to retrieve the page and continue on with
scrapy `selectors`, `item loaders` etc. Though this is not recommended
approach since you would be missing out on all of the features scrapy has to
offer.
official scrapy tutorial for beginners:
<http://doc.scrapy.org/en/latest/intro/tutorial.html>
|
Where does my embedded python stdout go?
Question: Consider the following
[MWE](https://en.wikipedia.org/wiki/Minimal_Working_Example):
#include <Python.h>
#include <stdio.h>
int main(void) {
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
printf("Test 4\n");
return 0;
}
When I compile and run this as normal i get the expected output:
$ ./test
Test 1
Test 2
Test 3
Test 4
But when I redirect the output I get nothing from the python code:
$ ./test | cat
Test 1
Test 2
Test 4
What is happening? And more importantly how do I get my python output written
to stdout like expected?
Answer: When `stdout` refers to a terminal, the output is line buffered otherwise
which is block or fully buffered, won't output until the block is full.
To make the output line buffered when `stdout` refers to non-terminal, set the
mode with [setvbuf](http://linux.die.net/man/3/setvbuf)
And you have to call `Py_Finalize()` to have `libpython` close its I/O handle.
#include <Python.h>
#include <stdio.h>
int
main(int argc, char **argv) {
//setlinebuf(stdout);
setvbuf(stdout, NULL, _IOLBF, 0);
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
Py_Finalize();
printf("Test 4\n");
return 0;
}
|
Create a graphic with xls using Pylab in Python
Question: I'm using Python 3.4.1. I want to create a graphic using xls files instead of
csv. How can I do ? Can I create a graphic using xls files without converting
them ?
from pylab import*
name = []
value = []
readFile = open('fichier_test.xls', 'r').read()
eachline = readFile.split('\n')
for line in eachline:
split = line.split(';')
name.append()
value.append(split[1])
value.append(float(split[1]))
pos = arange(len(name))+.5
barh(pos, value, align='center',color='blue')
yticks(pos, name)
show()
Answer: You can use the `xlrd` [library](https://pypi.python.org/pypi/xlrd) for python
to import the data. To print all the rows in your datasheet,
import xlrd
workbook = xlrd.open_workbook('fichier_test.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
for row in range(num_rows):
print(worksheet.row(row))
You can then extract, plot, etc with matplotlib.
|
Using South migrations with IBM Bluemix
Question: For a new app using Django 1.6, I am trying to create a `run.sh` that will run
the initial commands on Bluemix.
I found an answer
[here](https://developer.ibm.com/answers/questions/165725/unable-to-deploy-a-
python-django-application.html) that gives a run.sh file for the in-built
migration that is supported in Django 1.7+
#!/bin/bash
if [ -z "$VCAP_APP_PORT" ];
then SERVER_PORT=80;
else SERVER_PORT="$VCAP_APP_PORT";
fi
echo [$0] port is------------------- $SERVER_PORT
python manage.py makemigrations
python manage.py migrate
echo "from django.contrib.auth.models import User; User.objects.create_superuser(username='username',password='password',email='[email protected]')" | python manage.py shell
echo [$0] Starting Django Server...
python manage.py runserver --noreload 0.0.0.0:$SERVER_PORT
Is there an idempotent way to run the equivalent commands (`schemamigration
--auto`, `migrate`) in South?
Answer: I would strongly advice against creating your migrations on production. You
should create them in your local development environment, and test them before
you commit them along with the corresponding changes in your codebase.
The migrations are written in python files in a /migrations/ folder. You
should commit these files to your repository and push them to Bluemix (or
otherwise copy them). So manage.py schemamigration should only be run in
development and committed/pushed, and manage.py migrate can then safely be run
wherever you deploy your project.
|
Parsing a complex JSON object with Python: search a specific key/value pair
Question: **General question** : how can I search a specific `key:value` pair in a JSON
using Python?
**Details for the specific case** : I'm reading ~ 45'000 JSON objects, each
one of them look [like this
one](http://opac.sbn.it/opacmobilegw/search.json?any=Per%20la%20inaugurazione%20dell%27Asilo%20infantile%20Strozzi%20nei%20locali%20della%20caserma%20Filippini%20gi%C3%A0%20convento%20della%20Vittoria%20/%20parole%20di%20mons.%20Carlo%20Savoia&type=0&start=0&rows=3).
As you can see, inside every JSON there are several dictionaries that have the
same keys (but different values): `"facetName`, `"facetLabel"`,
`"facetValues"`.
I'm interested in the dictionary that starts with `"facetName": "soggettof"`,
that goes like:
{
"facetName": "soggettof",
"facetLabel": "Soggetto",
"facetValues": [
[
"chiesa - storia - documenti",
"chiesa - storia - documenti",
"1"
],
[
"espiazione - mare mediterraneo <bacino> - antichita - congressi - munster - 1999",
"espiazione - mare mediterraneo <bacino> - antichita - congressi - munster - 1999",
"1"
],
[
"lega rossa combattenti - storia",
"lega rossa combattenti - storia",
"1"
],
[
"pavia - storia ecclesiastica - origini-sec. 12.",
"pavia - storia ecclesiastica - origini-sec. 12.",
"1"
],
[
"pavia <diocesi> - storia - origini-sec. 12.",
"pavia <diocesi> - storia - origini-sec. 12.",
"1"
],
[
"persia - sviluppo economico - 1850-1900 - fonti diplomatiche inglesi",
"persia - sviluppo economico - 1850-1900 - fonti diplomatiche inglesi",
"1"
]
Please note, that not all the JSON objects have that.
How can I grab the values of the `facetValues` list, but only in the
dictionary that I'm interested in?
Answer: I found your question a little confusing, partially because the data shown in
it was _not_ really the JSON-object you needed to extract the information from
-- but was instead an example of a sub-JSON-object you wanted to extract it
from. Fortunately you had a
[link](http://opac.sbn.it/opacmobilegw/search.json?any=Per%20la%20inaugurazione%20dell%27Asilo%20infantile%20Strozzi%20nei%20locali%20della%20caserma%20Filippini%20gi%C3%A0%20convento%20della%20Vittoria%20/%20parole%20di%20mons.%20Carlo%20Savoia&type=0&start=0&rows=3)
to the outer-most container JSON-object (even though the data in corresponding
sub-JSON-object in it was different). This is the link data:
json_obj = {"numFound":1,"start":0,"rows":3,"briefRecords":[{"progressivoId":0,"codiceIdentificativo":"IT\\ICCU\\LO1\\0120590","autorePrincipale":"Savoia, Carlo","titolo":"Per la inaugurazione dell'Asilo infantile Strozzi nei locali della caserma Filippini già convento della Vittoria / parole di mons. Carlo Savoia","pubblicazione":"Mantova : Tip. Eredi Segna, 1870","livello":"Monografia","tipo":"Testo a stampa","numeri":[],"note":[],"nomi":[],"luogoNormalizzato":[],"localizzazioni":[],"citazioni":[]}],"facetRecords":[{"facetName":"level","facetLabel":"Livello bibliografico","facetValues":[["Monografia","m","1"]]},{"facetName":"tiporec","facetLabel":"Tipo di documento","facetValues":[["Testo a stampa","a","1"]]},{"facetName":"nomef","facetLabel":"Autore","facetValues":[["savoia, carlo","savoia, carlo","1"]]},{"facetName":"soggettof","facetLabel":"Soggetto","facetValues":[["mantova - asili infantili","mantova - asili infantili","1"]]},{"facetName":"luogof","facetLabel":"Luogo di pubblicazione","facetValues":[["mantova","mantova","1"]]},{"facetName":"lingua","facetLabel":"Lingua","facetValues":[["italiano","ita","1"]]},{"facetName":"paese","facetLabel":"Paese","facetValues":[["italia","it","1"]]}]}
It's important to have this outer-most container because it is through it you
will have to begin drilling-down to the portion you want. Once you have the
actaul data you may need to reformat it to make its structure clear. You can
do this by hand, or have the computer do it with `print(json.dumps(json_obj,
indent=2))` although the results from that can sometimes have a little too
much white space in them (which can be counterproductive).
That being the case here, below is the more succinct version I came up doing
it manually that still let's me see the overall layout of the data:
json_obj = {"numFound" : 1,
"start" : 0,
"rows" : 3,
"briefRecords" : [
{"progressivoId" : 0,
"codiceIdentificativo" : "IT\\ICCU\\LO1\\0120590",
"autorePrincipale" : "Savoia, Carlo",
"titolo" : "Per la inaugurazione dell'Asilo infantile Strozzi nei locali della caserma Filippini già convento della Vittoria / parole di mons. Carlo Savoia",
"pubblicazione" : "Mantova : Tip. Eredi Segna, 1870",
"livello" : "Monografia",
"tipo" : "Testo a stampa",
"numeri" : [],
"note" : [],
"nomi" : [],
"luogoNormalizzato" : [],
"localizzazioni" : [],
"citazioni" : []
}
],
"facetRecords" : [
{"facetName" : "level" ,
"facetLabel" : "Livello bibliografico" ,
"facetValues" : [["Monografia" , "m" , "1"]]},
{"facetName" : "tiporec" ,
"facetLabel" : "Tipo di documento" ,
"facetValues" : [["Testo a stampa" , "a" , "1"]]},
{"facetName" : "nomef" ,
"facetLabel" : "Autore" ,
"facetValues" : [["savoia, carlo" , "savoia, carlo" , "1"]]},
{"facetName" : "soggettof" ,
"facetLabel" : "Soggetto" ,
"facetValues" : [["mantova - asili infantili" , "mantova - asili infantili" , "1"]]},
{"facetName" : "luogof" ,
"facetLabel" : "Luogo di pubblicazione" ,
"facetValues" : [["mantova" , "mantova" , "1"]]},
{"facetName" : "lingua" ,
"facetLabel" : "Lingua" ,
"facetValues" : [["italiano" , "ita" , "1"]]},
{"facetName" : "paese" ,
"facetLabel" : "Paese" ,
"facetValues" : [["italia" , "it" , "1"]]}
]
}
Once you have something like this, it usually makes it fairly easy to
determine what code is needed. In this case it's:
target_facet_name = "soggettof"
for record in json_obj["facetRecords"]:
if record["facetName"] == target_facet_name:
for value in record["facetValues"]:
print value
Since `facetRecords` is a list, a linear search through them is required to
find the one(s) desired.
|
PyZDDE (Python Zemax DDE)
Question: It's first time when I use this tool (pyzdde). When I run simple program error
has occurred!
#**************** Add PyZDDE to Python search path **********
import sys
PyZDDEPath = 'C:\PyZDDE' # Assuming PyZDDE was unzipped here!
if PyZDDEPath not in sys.path:
sys.path.append(PyZDDEPath)
#************************************************************
import pyzdde.zdde as pyz
#Create a PyZDDE object
link = pyz.createLink()
ERROR: Unable to establish a conversation with server (err=0x400a). ZEMAX may
not be running! Could not initiate instance.
Answer: The error message says that PyZDDE couldn't create a link to communicate with
Zemax as Zemax may not be running. So, were you running Zemax when executing
the above code?
By the way, you don't need to use the above template any more to use PyZDDE.
Now, there is a pyzdde [PyPI package](https://pypi.python.org/pypi/PyZDDE). So
you can just use pip to install pyzdde. The installation instructions are
[here](https://github.com/indranilsinharoy/PyZDDE#install-pyzdde-from-pypi).
After installing, open Zemax, and then try to run the [spiral spot
example](https://github.com/indranilsinharoy/PyZDDE/wiki#example).
Hope that helps.
|
MST Clustering using Python
Question: I want to make clusters of nodes based on edges of a minimum spanning tree. I
used scipy to create minimum spanning tree. The following code:
file = open('/home/deep/Desktop/Lalit_jee/spanning.txt', 'w')
import euc_dist
import stan_devia
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import minimum_spanning_tree
matrix = euc_dist.euc_matrix
matrix1 = matrix
new_mat = [[]]
for i in range(len(matrix1)):
for j in range(len(matrix1)):
if j <= i:
matrix1[i][j] = 0
X = csr_matrix(matrix1)
min_span = minimum_spanning_tree(X)
print >> file, min_span
produced the output as follows:
(0, 2) 3.0
(0, 9) 2.0
(1, 8) 3.0
(1, 9) 4.0
(2, 3) 15.0
(3, 7) 2.0
(4, 5) 6.0
(4, 8) 3.0
(6, 7) 36.0
which indicates a graph as shown in the figure:
! [spanning tree](http://imgur.com/b57UVUC)
I took threshold as 4. So now I must have the following output:
! [Clusters](http://imgur.com/q8hnehB)
In the case of data, I must have the following:
(0,9) 2.0
(0,2) 3.0
(3,7) 2.0
(8,1) 3.0
(8,4) 3.0
(5,5) 0.0
(6,6) 0.0
Please tell me the most pythonic way to achieve this output. Thanks in
advance...
Answer: If loops are not required you can use something like this:
[[i for i in row if i < threshold else 0]
for row in min_span.toarray().astype(int)
]
This will give you resulting matrix as an array
|
Python str.translate VS str.replace
Question: Why in **_Python_** `replace` is ~1.5x quicker than `translate`?
In [188]: s = '1 a 2'
In [189]: s.replace(' ','')
Out[189]: '1a2'
In [190]: s.translate(None,' ')
Out[190]: '1a2'
In [191]: %timeit s.replace(' ','')
1000000 loops, best of 3: 399 ns per loop
In [192]: %timeit s.translate(None,' ')
1000000 loops, best of 3: 614 ns per loop
Answer: Assuming Python 2.7 (because I had to flip a coin without it being stated), we
can find the source code for
[string.translate](https://docs.python.org/2/library/string.html#string.translate)
and
[string.replace](https://docs.python.org/2/library/string.html#string.replace)
in `string.py`:
>>> import inspect
>>> import string
>>> inspect.getsourcefile(string.translate)
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/string.py'
>>> inspect.getsourcefile(string.replace)
'/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/string.py'
>>>
Oh, we can't, `as string.py` starts with:
"""A collection of string operations (most are no longer used).
Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object.
I upvoted you because you started down the path of profiling, so let's
continue down that thread:
from cProfile import run
from string import ascii_letters
s = '1 a 2'
def _replace():
for x in range(5000000):
s.replace(' ', '')
def _translate():
for x in range(5000000):
s.translate(None, ' ')
for replace:
run("_replace()")
5000004 function calls in 2.059 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.976 0.976 2.059 2.059 <ipython-input-3-9253b3223cde>:8(_replace)
1 0.000 0.000 2.059 2.059 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 1.033 0.000 1.033 0.000 {method 'replace' of 'str' objects}
1 0.050 0.050 0.050 0.050 {range}
and for translate:
run("_translate()")
5000004 function calls in 1.785 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.977 0.977 1.785 1.785 <ipython-input-3-9253b3223cde>:12(_translate)
1 0.000 0.000 1.785 1.785 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 0.756 0.000 0.756 0.000 {method 'translate' of 'str' objects}
1 0.052 0.052 0.052 0.052 {range}
our number of function calls are the same, not that more function calls means
that a run will be slower, but it's typically a good place to look. What's fun
is that `translate` ran faster on my machine than `replace`! Consider that the
fun of not testing changes in isolation -- not that it matters because we only
are concerned with being able to tell why there _could_ be a difference.
In any case, we at least now know that there's maybe a performance difference
and it does exist when evaluating the string object's method (see `tottime`).
The `translate` `__docstring__` suggests that there's a translation table in
play, while the replace only mentions old-to-new-substring replacement.
Let's turn to our old buddy
[`dis`](https://docs.python.org/2/library/dis.html) for hints:
from dis import dis
replace:
def dis_replace():
'1 a 2'.replace(' ', '')
dis(dis_replace)
dis("'1 a 2'.replace(' ', '')")
3 0 LOAD_CONST 1 ('1 a 2')
3 LOAD_ATTR 0 (replace)
6 LOAD_CONST 2 (' ')
9 LOAD_CONST 3 ('')
12 CALL_FUNCTION 2
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
and `translate`, which ran faster for me:
def dis_translate():
'1 a 2'.translate(None, ' ')
dis(dis_translate)
2 0 LOAD_CONST 1 ('1 a 2')
3 LOAD_ATTR 0 (translate)
6 LOAD_CONST 0 (None)
9 LOAD_CONST 2 (' ')
12 CALL_FUNCTION 2
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
unfortunately, the two look identical to `dis`, which means that we should
start looking to the string's C source here (found by going to the python
source code for the version of Python I'm using right
now)](<https://hg.python.org/cpython/file/a887ce8611d2/Objects/stringobject.c>).
Here's the [source for
translate](https://hg.python.org/cpython/file/a887ce8611d2/Objects/stringobject.c#l2198).
If you go through the comments, you can see that there are multiple `replace`
function definition lines, based on the length of the input.
Our options for substring replacement are:
[replace_substring_in_place](https://hg.python.org/cpython/file/a887ce8611d2/Objects/stringobject.c#l2552)
/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_substring_in_place(PyStringObject *self,
and
[replace_substring](https://hg.python.org/cpython/file/a887ce8611d2/Objects/stringobject.c#l2672):
/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_substring(PyStringObject *self,
and
[replace_delete_single_character](https://hg.python.org/cpython/file/a887ce8611d2/Objects/stringobject.c#l2415):
/* Special case for deleting a single character */
/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_delete_single_character(PyStringObject *self,
char from_c, Py_ssize_t maxcount)
`'1 a 2'.replace(' ', '')` is a len(self)==6, replacing 1 char with an empty
string, making it a `replace_delete_single_character`.
You can check out the function body for yourself, but the answer is "the C
function body runs faster in `replace_delete_single_character` than
`string_translate` for this specific input.
Thank you for asking this question.
|
PermissionError [errno 13] when running openpyxl python script in Komodo
Question: I am having trouble using openpyxl scripts in Komodo edit 9 and python 3.4 on
Windows 7. I copied some openpyxl code to learn, but it won't execute from
Komodo. I receive a permission error 13. I checked my path and python34 is
present. The same script will run when I use IDLE or Command Prompt. My Komodo
command is currently: %(python3) -u %F Any ideas on what may be causing this
issue? The code and error are included below
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
wb = Workbook()
dest_filename = 'empty_book.xlsx'
ws1 = wb.active
ws1.title = "range names"
for row in range(1, 40):
ws1.append(range(600))
ws2 = wb.create_sheet(title="Pi")
ws2['F5'] = 3.14
ws3 = wb.create_sheet(title="Data")
for row in range(10, 20):
for col in range(27, 54):
_ = ws3.cell(column=col, row=row, value="%s" % get_column_letter(col))
print(ws3['AA10'].value)
wb.save(filename = dest_filename)
\-------Begin Error-----------
AA
Traceback (most recent call last):
File "C:\Users\PF15043\Desktop\Scripts\Ggizmo\excelReader.py", line 26, in <module>
wb.save(filename = dest_filename)
File "C:\Python34\lib\site-packages\openpyxl-2.3.0b1-py3.4.egg\openpyxl\workbook\workbook.py", line 254, in save
save_workbook(self, filename)
File "C:\Python34\lib\site-packages\openpyxl-2.3.0b1-py3.4.egg\openpyxl\writer\excel.py", line 195, in save_workbook
writer.save(filename, as_template=as_template)
File "C:\Python34\lib\site-packages\openpyxl-2.3.0b1-py3.4.egg\openpyxl\writer\excel.py", line 177, in save
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Python34\lib\zipfile.py", line 923, in __init__
self.fp = io.open(file, modeDict[mode])
PermissionError: [Errno 13] Permission denied: 'empty_book.xlsx'
Thanks for the help.
Answer: This is simply an error from the operating system telling you that you don't
have permissions to create a file where you're trying to. You should specify
the full path of the file you're trying to create.
|
ImportError: No module named 'selenium'
Question: I'm trying to write a script to check a website. It's the first time I'm using
selenium. I'm trying to run the script on a OSX system. Although I checked in
/Library/Python/2.7/site-packages and selenium-2.46.0-py2.7.egg is present,
when I run the script it keeps telling me that there is no selenium module to
import.
This is the log that I get when I run my code:
>
> Traceback (most recent call last):
> File "/Users/GiulioColleluori/Desktop/Class_Checker.py", line 10, in
> <module>
> from selenium import webdriver
> ImportError: No module named 'selenium'
>
If you could please let me know if you have any idea of what could be causing
the issue that'd be greatly appreciated.
Thank you.
Answer: If you have pip installed you can install selenium like so.
`pip install selenium`
or depending on your permissions:
`sudo pip install selenium`
As you can see from this question [pip vs
easy_install](http://stackoverflow.com/questions/3220404/why-use-pip-over-
easy-install) pip is a more reliable package installer as it was built to
improve easy_install.
I would also suggest that when creating new projects you do so in virtual
environments, even a simple selenium project. You can read more about virtual
environments [here](http://docs.python-guide.org/en/latest/dev/virtualenvs/).
In fact pip is included out of the box with virtualenv!
|
Python Dictionary Trouble: Grouping by elements in tuple key
Question: so I have a dictionary that looks something like this, with 4 element tuples
as keys, and a list of lists as corresponding values. (yay indexing)
{('A002', 'R051', '02-00-00', 'LEXINGTON AVE'): [[datetime.datetime(2015, 6, 20, 0, 0),
750],
[datetime.datetime(2015, 6, 21, 0, 0),
576],
[datetime.datetime(2015, 6, 22, 0, 0),
1486],
[datetime.datetime(2015, 6, 23, 0, 0),
595],
[datetime.datetime(2015, 6, 24, 0, 0),
841],
[datetime.datetime(2015, 6, 25, 0, 0),
1072],
[datetime.datetime(2015, 6, 26, 0, 0),
1049]],
('A002', 'R051', '02-00-01', 'LEXINGTON AVE'): [[datetime.datetime(2015, 6, 20, 0, 0),
670],
[datetime.datetime(2015, 6, 21, 0, 0),
457],
[datetime.datetime(2015, 6, 22, 0, 0),
1189],
[datetime.datetime(2015, 6, 23, 0, 0),
505],
[datetime.datetime(2015, 6, 24, 0, 0),
665],
[datetime.datetime(2015, 6, 25, 0, 0),
354],
[datetime.datetime(2015, 6, 26, 0, 0),
651]]}
I want to modify this dictionary so that I combine values for all keys that
have the same 1st, 2nd, and 4th tuple elements. (as the two keys up there do).
I would like to combine those two key tuples into one key tuple (so that my
combined key is just `('A002', 'R051', 'LEXINGTON AVE')`) and combine the
values as well. Is this possible in python?
So, for instance, the first value would be [datetime.datetime(2015, 6, 20, 0,
0), 1420] ----- which is 670 + 750, in this case
Thanks in advance.
Answer: Yep, just go ahead and make another dictionary. Supposing the data you have
above is stored in `data`, we'll make a dictionary called `short_data`:
short_data = {}
for key, value in data.items():
short_key = (key[0], key[1], key[3])
if short_key in short_data:
short_data[short_key].extend(value)
else:
short_data[short_key] = value
Or, if you don't mind using a `defaultdict`, you can make this shorter:
import collections
short_data = collections.defaultdict(list)
for key, value in data.items():
short_key = (key[0], key[1], key[3])
short_data[short_key].extend(value)
If you'd like to combine the values by adding them, I'd suggest using a
`Counter`:
import collections
short_data = collections.defaultdict(collections.Counter)
for key, value in data.items():
short_key = (key[0], key[1], key[3])
short_data[short_key] += collections.Counter(dict(data[key]))
|
How to give input to a batch file using Python script?
Question: Let's say I have a batch file, which asks me for my name as input. I put my
name enter. This is the manual way.
But I wanted to try something with Python. Is it possible that I make a
variable in Python script and put my name in the variable and pass that
variable to the bat file when it asks for input?
The very first step of my bat file is to ask me my name. Asking name batch
file is for test purpose. My main batch file has this code:
@ECHO OFF
:choice
set /P c=Do you want to continue [Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice
:yes
"scripts\enter.py" yes
goto :continue
:no
"scripts\kick_out.py" no
:continue
pause
exit
So, I hope this helps. I want to pass about 2 inputs. First `Y` and other when
it calls `enter.py` it asks my login details. My username and password. So, I
need to make 3 inputs. How can I do that?
Answer: It is feasible : I use it to inject attack string which use non-printable
ascii characters (like null bytes).
Example using Python 3 :
> inject_string.py
import ctypes
import time
import subprocess
import binascii
if __name__ =="__main__":
response = "Y"
p = subprocess.Popen("echo.bat", stdin = subprocess.PIPE)
time.sleep(2)
p.stdin.write(bytes(response, 'ascii')) #Answer the question
print("injected string :", response)
> echo.bat
@ECHO OFF
:choice
set /P c=Do you want to continue [Y/N]?
if /I "%c%" EQU "Y" goto :yes
if /I "%c%" EQU "N" goto :no
goto :choice
:yes
echo "User has typed yes"
goto :continue
:no
echo "User has typed no"
:continue
pause
> Output
python inject_string.py
Do you want to continue [Y/N]?injected string : Y
"User has typed yes"
|
How to configure Apache 2 to run a Python script from a Ruby CGI app with %x{}
Question: My Ruby CGI app is very simple, I would like to call a Python script, for
example `youtube-dl`, or `youtube-upload` with `%x{youtube-dl --help}`
For the sake of simplicity, I would like to print only the help page of the
`youtube-dl` Python script. So my Ruby script is also very simple:
#!/usr/bin/ruby
require "cgi"
cgi=CGI.new(:accept_charset => "UTF-8")
url=cgi['url']
puts "Content-Type: text/plain; charset=\"UTF-8\""
puts "Access-Control-Allow-Origin: *"
puts
puts url
puts "-----------------------------------"
puts %x{youtube-dl --help 2>&1}
Then I can invoke this CGI app called `ytdl` with <http://example.com/cgi-
bin/ytdl?url=a_youtube_url>. Unfortunately I get only a lot of error messages
from the Python interpreter which is unable to import some packages,
especially site-packages:
Traceback (most recent call last):
File "/usr/bin/youtube-dl", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/python3.4/site-packages/pkg_resources/__init__.py", line 36, in <module>
import plistlib
File "/usr/lib/python3.4/plistlib.py", line 65, in <module>
from xml.parsers.expat import ParserCreate
File "/usr/lib/python3.4/xml/parsers/expat.py", line 4, in <module>
from pyexpat import *
ImportError: /usr/lib/python3.4/lib-dynload/pyexpat.cpython-34m.so: undefined symbol: XML_SetHashSalt
I think I would configure my Apache 2 web server to provide some environment
variables for the Python interpereter, where it can find the packages.
Unfortunately I have no experience with Python, I only learned Ruby till now.
My Apache server runs CGI apps as user `daemon`, and when I login as `daemon`
I can run the `youtube-dl` script without error messages.
Apache provide these environment for my CGI apps (printed with `puts
%x{env}`):
UNIQUE_ID=VZN9RyX3N7MAAAs95zsAAAAI
RUBYOPT=rubygems
GEM_HOME=/home/XXXXXX/.gem/ruby/2.2.0
HTTP_USER_AGENT=Opera/9.80 (X11; Linux i686) Presto/2.12.388 Version/12.16
HTTP_HOST=xx.xxx.xx.xxx
HTTP_ACCEPT=text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
HTTP_ACCEPT_LANGUAGE=en-US,en;q=0.9
HTTP_ACCEPT_ENCODING=gzip, deflate
HTTP_CONNECTION=Keep-Alive
PATH=/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/home/XXXXXX/.gem/ruby/2.2.0/bin:/home/XXXXXX/util
LD_LIBRARY_PATH=/opt/lampp/lib:/opt/lampp/lib
SERVER_SIGNATURE=
SERVER_SOFTWARE=Apache/2.4.9 (Unix) OpenSSL/1.0.1g PHP/5.5.11 mod_perl/2.0.8-dev Perl/v5.16.3
SERVER_NAME=xx.xxx.xx.xxx
SERVER_ADDR=xx.xxx.xx.xxx
SERVER_PORT=80
REMOTE_ADDR=xx.x.xxx.xxx
DOCUMENT_ROOT=/opt/lampp/htdocs
REQUEST_SCHEME=http
CONTEXT_PREFIX=/cgi-bin/
CONTEXT_DOCUMENT_ROOT=/opt/lampp/cgi-bin/
[email protected]
SCRIPT_FILENAME=/opt/lampp/cgi-bin/ytdl
REMOTE_PORT=37798
GATEWAY_INTERFACE=CGI/1.1
SERVER_PROTOCOL=HTTP/1.1
REQUEST_METHOD=GET
QUERY_STRING=
REQUEST_URI=/cgi-bin/ytdl
SCRIPT_NAME=/cgi-bin/ytdl
Meanwhile I realized that when I set the environment variable (either in
Apache config httpd.conf with SetEnv directive, or with
`ENV['PYTHONHOME']=value` in my Ruby script) called PYTHONHOME to an empty
string "" or "/usr/lib" , the error message disappers, and I get another one:
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
When I set:
ENV['PYTHONHOME']="/usr/lib"
ENV['PYTHONPATH']="/usr/lib/python3.4"
I get another error message:
File "/usr/bin/youtube-dl", line 5, in <module>
from pkg_resources import load_entry_point
ImportError: No module named 'pkg_resources'
So my question is, how should I configure my Apache 2 webserver to make Python
scripts run and make them callable from other apps?
Answer: When you run an application in a subshell you have to be aware of the
environment being set up for that shell and application. The PATH and
variables will be nonexistent or very limited which can affect its ability to
find libraries.
Write a small CGI that outputs the Apache variables and environment passed to
the script, either as a web page or to the log or a file and examine the
results.
Also permissions and the user will be whatever the server sets up which is
usually very restricted.
Also, seriously consider _not_ using CGI. Instead use something more modern
and flexible. Sinatra works nicely with Apache using something like Passenger
to glue them together. Sinatra makes it really easy to do web-services, and
actually works so well you can often do without a heavyweight server like
Apache, especially during the development, test and early production stages. I
have an API used in-house that handles a lot of enterprise-critical requests
and it just cruises along.
|
How can i both register blueprint and add that app to flask-admin
Question: my Code:
__init__.py
from flask import Flask
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from user.user import mod as user
from user.models import User as userModel
app.register_blueprint(user, url_prefix='/user')
admin = Admin(app, name='My app')
admin.add_view(ModelView(userModel, db.session, name='userAdmin'))
user.py:
from flask import Blueprint, json
from flask.views import MethodView
mod = Blueprint('user', __name__)
class UserAPI(MethodView):
def get(self):
users = [
{'nickname': 'Chan'},
{'nickname': 'Hzz'},
]
return json.dumps(users)
mod.add_url_rule('/users/', view_func=UserAPI.as_view('users'))
models.py:
from app import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return "<User %s>" % self.username
i have a blueprint in my user app, and i've registered it, but when i want to
add this to my admin to manage the user data, it throws the below exception:
Traceback (most recent call last):
File "run.py", line 2, in <module>
from app import app
File "/home/chenhj/flask/multiapp/app/__init__.py", line 21, in <module>
admin.add_view(ModelView(userModel, db.session, name='chj'))
File "/home/chenhj/.virtualenvs/multiapp/local/lib/python2.7/site-packages/flask_admin/base.py", line 526, in add_view
self.app.register_blueprint(view.create_blueprint(self))
File "/home/chenhj/.virtualenvs/multiapp/local/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "/home/chenhj/.virtualenvs/multiapp/local/lib/python2.7/site-packages/flask/app.py", line 885, in register_blueprint
(blueprint, self.blueprints[blueprint.name], blueprint.name)
AssertionError: A blueprint's name collision occurred between <flask.blueprints.Blueprint object at 0x25e5d90> and <flask.blueprints.Blueprint object at 0x21b89d0>. Both share the same name "user". Blueprints that are created on the fly need unique names.
i am crazy about that
Answer: The collision is because you have a module name user and a blueprint called
user. Rename the blueprint to user_blueprint. From the code it seems you have
a folder called user, a module called user and a blueprint called user. You
can avoid problems later on with some descriptive names. Otherwise it is just
plain confusing.
|
Python mechanize download file with original filename
Question: Working on a python script to scraping multi files from a website.
The download form html is something like this:
<span>
<a class="tooltip" href="download.php?action=download&id=xxx&authkey=yyy&pass=zzz" title="Download">DL</a>
</span>
What I'm thinking of is:
f1 = open('scraping.log', 'a')
page = br.open(url)
html = page.read()
soup = BeautifulSoup(html)
for a in soup.select('a[href^="download.php?action=download"]'):
link = a.attrs.get('href')
print >>f1, link
br.retrieve(url+link, destination)
However, for the retrieve I have to state out the output filename. I want to
get the original filename instead of setting it as a random name. Is there any
way to do that? Moreover, as I want to add this script to run frequently in
crontab, is there a way for me to set us check the scraping.log and skip those
that have been downloaded before?
Answer: If you don't like "download.php", check for a [Content-Disposition
header](http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1),
e.g.:
Content-Disposition: attachment; filename="fname.ext"
And ensure the filename [complies with your
intent](http://www.ietf.org/rfc/rfc2183.txt):
> It is important that the receiving MUA not blindly use the suggested
> filename. The suggested filename SHOULD be checked (and possibly changed) to
> see that it conforms to local filesystem conventions, does not overwrite an
> existing file, and does not present a security problem (see Security
> Considerations below).
Python 2:
import re
import mechanize # pip install mechanize
br = mechanize.Browser()
r = br.open('http://yoursite.com')
#print r.info()['Content-Disposition']
unsafe_filename = r.info().getparam('filename') # Could be "/etc/evil".
filename = re.findall("([a-zA-Z0-9 _,()'-]+[.][a-z0-9]+)$", unsafe_filename)[0] # "-]" to match "-".
As for skipping links you've processed before,
f1 = open('scraping.log', 'a')
processed_links = f1.readlines()
page = br.open(url)
html = page.read()
soup = BeautifulSoup(html)
for a in soup.select('a[href^="download.php?action=download"]'):
link = a.attrs.get('href')
if not link in processed_links:
print >>f1, link
processed_links += [link]
br.retrieve(url+link, destination)
|
Copying excel rows via python
Question: I basically have one excel file with has the following entries in a particular
sheet
row[0][0]=hello
row[1][0]=bye
row[2][0]=hi
I want to copy these three rows into the number of rows present in the
original sheet, so that the modified sheet has the following.
row[0][0]=hello
row[1][0]=bye
row[2][0]=hi
row[3][0]=hello
row[4][0]=bye
row[5][0]=hi
row[6][0]=hello
row[7][0]=bye
row[8][0]=hi
My code is the below.
from xlutils.copy import copy
from xlrd import open_workbook
import xlwt
book=open_workbook("/Users/tusharbakaya/Desktop/test.xlsx")
book1=copy(book)
sheet=book.sheet_by_name('Sheet1')
sheet1=book1.get_sheet(0)
totalrows=sheet.nrows
print totalrows
for j in range(0,totalrows):
for i in range(0,totalrows):
row=sheet.cell_value(i,0)
sheet1.write(j+totalrows,0,row)
i+=1
j+=totalrows
book1.save("/Users/tusharbakaya/Desktop/test1.xls")
However, I get the following output
row[0][0]=hello
row[1][0]=bye
row[2][0]=hi
row[3][0]=hello
row[4][0]=hello
row[5][0]=hello
row[6][0]=hello
Not sure why this is happening.
Answer: The issue is that even if you change the loop variable `j` inside the loop,
that change would be overwritten with the next value from `range()` function.
An example to show this -
>>> for i in range(10):
... print(i)
... i = 1000
...
0
1
2
3
4
5
6
7
8
9
But your code is depending on this to happen, instead you should try to set to
i+j*totalrows (everytime) and start j from `1`. And the logic inside the inner
loop is also a bit wrong, you should depend on `i` variable as well to set the
values in new workbook.
So the code would become -
from xlutils.copy import copy
from xlrd import open_workbook
import xlwt
book=open_workbook("/Users/tusharbakaya/Desktop/test.xlsx")
book1=copy(book)
sheet=book.sheet_by_name('Sheet1')
sheet1=book1.get_sheet(0)
totalrows=sheet.nrows
print totalrows
for j in range(0,totalrows):
for i in range(0,totalrows):
row=sheet.cell_value(i,0)
sheet1.write(i+(j*totalrows),0,row)
book1.save("/Users/tusharbakaya/Desktop/test1.xls")
or you can use a `while` loop instead of `for` loop and
Example for while loop -
from xlutils.copy import copy
from xlrd import open_workbook
import xlwt
book=open_workbook("/Users/tusharbakaya/Desktop/test.xlsx")
book1=copy(book)
sheet=book.sheet_by_name('Sheet1')
sheet1=book1.get_sheet(0)
totalrows=sheet.nrows
print totalrows
j,k = 0, 0
while k < totalrows
for i in range(0,totalrows):
row=sheet.cell_value(i,0)
sheet1.write(i+j,0,row)
j+=totalrows
k += 1
book1.save("/Users/tusharbakaya/Desktop/test1.xls")
|
Overload python function depending on the execution path
Question: I have a `main.py` script in a folder A. Nowaday, I use a separate file
`test.py` in order to test the result depending on the tested element.
I wanna use the `test.py` in the execution folder and not the one in the
folder A.
`main.py` in folder somewhere:
def test():
classic way to test
if __name__ == '__main__':
prepare the test
test()
In a folder unknow in the `main.py` in wanna have a file `test.py`:
def test():
specific test if I execute the script in this folder
Can I do this and how?
Answer: For your specific requirement , you can move the `test()` function to another
python file lets say `test.py` , and then import it as -
from test import test
When python is trying to find the `test.py` it consults the `sys.path` (read
PYTHONPATH) list , which contains the list of all directories inside which
python will try to locate the `test.py` .
Now when running a script, python automatically appends the current directory
(from where the script is run) as the first element of sys.path (Please note
this is not the location of the script, rather the location in command
line/terminal from where the script was run) .
Then some standard libraries as well as the information in PYTHONPATH.
As an example , I had set my PYTHONPATH variable in windows to `D:\\` and the
`sys.path` when my script was run from `D:\Python\test\shared` was -
['D:\\Python\\test\\shared', 'C:\\Python34\\lib\\site-packages\\setuptools-17.1.1-py3.4.egg', 'C:\\Python34\\lib\\site-packages\\openpyxl-2.2.4-py3.4.egg', 'D:\\', 'C:\\windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
Now when trying to find `test.py` , python will look through the above list
sequentially (from first element to last) till `test.py` is found, if not
found will throw `ImportError` , if found it loads the `test.py` from the
first location it found it in (it does not search in later directories , if it
has been found once).
So in your case, you can keep the classic `test.py` in some common location
and then add that path to `PYTHONPATH` , and then when you want to change the
logic of `test()` function , you can create a `test.py` in your current
directory with a `test()` function containing the new logic, and when you run
`main.py` since `test.py` exists in your current directory, that would be
loaded (instead of the other `test.py`)
But please note you should deal with this carefully, since I have seen lots of
people getting different errors ,because they mess up their imports (having
mutliple files with same name) and many of them present in the `PYTHONPATH`
variable.
|
How to insert a character in a string considering a few conditions in python
Question: Say I will ask the user to input a string. How can I add a character at the
end of every word that ends in "a", "e" or "o"?
For example, from
f = "O, awesome people, help me if ya will"
I'd have
f = "Oh, awesomeh peopleh, help meh if yah will"
Answer: Use `re.sub`
re.sub(r'(?i)([aeo])\b', r'\1h', s)
* `(?i)` helps to do case-insensitive match.
* `([aeo])` captures a,e,o only if it's followed by a word boundary.
**Example:**
>>> import re
>>> f = "O, awesome people, help me if ya will"
>>> re.sub(r'(?i)([aeo])\b', r'\1h', f)
'Oh, awesomeh peopleh, help meh if yah will'
|
maya to fbx with custom attributes
Question: I have a maya scene where each mesh has a list of custom attributes on the
shape node that I add dynamically using python.
import maya.cmds as cmds
import maya.mel as mm
#get mesh objects.
meshes = maya.cmds.ls(type="mesh")
for mesh in meshes:
cmds.select(mesh)
#check if attribute exists, if not, create.
if not mm.eval( 'attributeExists "test" "%s"' % mesh):
cmds.addAttr( shortName='tst', longName='test', dataType="string")
When I export to .fbx and re-import, these attributes and their values are
gone.
How can I keep all these values upon export?
Answer: Unfortunately, you can't. From the [maya
docs](http://knowledge.autodesk.com/support/maya/learn-
explore/caas/CloudHelp/cloudhelp/2015/ENU/Maya/files/GUID-
AA3B8EA4-DDFB-4B0F-9654-2BF6B8781AE7-htm.html):
> You can export Maya transform node custom attributes to the user properties
> of FbxNode. However, you cannot export Maya shape node custom attributes,
> such as mesh node, to FbxGeometry. This is because FbxGeometry does not
> currently support user properties.
Your best bet is probably to try putting the custom attributes on a non-shape
node if possible, or else exploring other export formats like
[alembic](http://knowledge.autodesk.com/support/maya/learn-
explore/caas/CloudHelp/cloudhelp/2015/ENU/Maya/files/Alembic-Export-htm.html)
or your own custom format.
|
Django - Slugs - Key (slug)=() is duplicated
Question: just started fooling around with Django and came across a link
[here](http://www.tangowithdjango.com/book17/chapters/models_templates.html)
on how to create slugs. I was told to perform the following changes to an
existing model:
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
This worked out pretty well until I tried to migrate the database using:
python manage.py makemigrations
The above asked for a default value so following the guide, I gave it ''.
Then:
python manage.py migrate
The above returned "DETAIL: Key (slug)=() is duplicated."
I'm not entirely sure why this happened. Perhaps it's because I'm adding a new
field that is unique and I can't populate it with ''? If so, what do I have to
do in order to populate the database?
Answer: The documentation [explains how to migrate in these
circumstances](https://docs.djangoproject.com/en/1.8/howto/writing-
migrations/#migrations-that-add-unique-fields). A quick summary:
* create the field without unique=True
* create a migration with a RunPython function that iterates through all Categories and calls save on them, which will populate the slug
* create a final migration which sets unique=True.
|
Sequence of object cleanup and functions called by atexit in Python module
Question: I am integrating a legacy C++ library with Python using boost-python. The
legacy library has some global initialization and then the classes in it use
application wide data. I need to ensure that the shutdown function of the
legacy library is called after all wrapped objects are destroyed and thought
this might be achieved by registering a shutdown function using atexit.
However, I found that the wrapped objects are being cleaned up after atexit
calls the shutdown function, causing multiple segfaults within the legacy
library!
I can achieve the desired behavior by calling del on the wrapped objects
before exiting, but was hoping to leave deletion to Python. I have checked out
the red warning box in the [documentation of
object.**__del__**](https://docs.python.org/2/reference/datamodel.html#object.__del__),
and am wondering if my ideal world is unreachable.
Any suggestions for ensuring a shutdown method is called after all objects are
cleaned up when wrapping legacy code in a python module?
Some platform details in case they are important:
* Python 2.7.2
* Visual Studio 2013
* 64-bit build
Minimal code:
#include <iostream>
#include <boost/python.hpp>
using namespace std;
namespace legacy
{
void initialize() { cout << "legacy::initialize" << endl; }
void shutdown() { cout << "legacy::shutdown" << endl; }
class Test
{
public:
Test();
virtual ~Test();
};
Test::Test() { }
Test::~Test() { cout << "legacy::Test::~Test" << endl; }
}
BOOST_PYTHON_MODULE(legacy)
{
using namespace boost::python;
legacy::initialize();
class_<legacy::Test>("Test");
def("_finalize", &legacy::shutdown);
object atexit = object(handle<>(PyImport_ImportModule("atexit")));
object finalize = scope().attr("_finalize");
atexit.attr("register")(finalize);
}
Once compiled, this can be run using python with the following input and
outputs being displayed:
> >>> import legacy
> legacy::initialize
> >>> test = legacy.Test()
> >>> ^Z
> legacy::shutdown
> legacy::Test::~Test
Answer: In short, create a guard type that will initialize and shutdown the legacy
library in its constructor and destructor, then manage the guard via a smart
pointer in each exposed object.
* * *
There are some subtle details that can make getting the destruction process
correct difficult:
* The order of destruction for objects and objects in modules in [`Py_Finalize()`](https://docs.python.org/2/c-api/init.html#c.Py_Finalize) is random.
* There is no finalization of a module. In particular, dynamically loaded extension modules are not unloaded.
* The legacy API should only be shutdown once all objects using it are destroyed. However, the objects themselves may not be aware of one another.
To accomplish this, the Boost.Python objects need to coordinate when to
initialize and shutdown the legacy API. These objects also need to have
ownership over the legacy object that uses the legacy API. Using the [single
responsibility
principle](https://www.wikiwand.com/en/Single_responsibility_principle), one
can divide the responsibilities into a few classes.
One can use the [resource acquisition is
initialization](https://www.wikiwand.com/en/Resource_Acquisition_Is_Initialization)
(RAII) idiom to initialize and shutdown the legacy AP. For example, with the
following `legacy_api_guard`, when a `legacy_api_guard` object is constructed,
it will initialize the legacy API. When the `legacy_api_guard` object is
destructed, it will shutdown the legacy API.
/// @brief Guard that will initialize or shutdown the legacy API.
struct legacy_api_guard
{
legacy_api_guard() { legacy::initialize(); }
~legacy_api_guard() { legacy::shutdown(); }
};
As multiple objects will need to share management over when to initialize and
shutdown the legacy API, one can use a smart pointer, such as
`std::shared_ptr`, to be responsible for managing the guard. The following
example lazily initializes and shutdown the legacy API:
/// @brief Global shared guard for the legacy API.
std::weak_ptr<legacy_api_guard> legacy_api_guard_;
/// @brief Get (or create) guard for legacy API.
std::shared_ptr<legacy_api_guard> get_api_guard()
{
auto shared = legacy_api_guard_.lock();
if (!shared)
{
shared = std::make_shared<legacy_api_guard>();
legacy_api_guard_ = shared;
}
return shared;
}
Finally, the actual type that will be embedded into the Boost.Python object
needs to obtain a handle to the legacy API guard before creating an instance
of the legacy object. Additionally, upon destruction, the legacy API guard
should be released after the legacy object has been destroyed. One non-
intrusive way to accomplish this is to use provide a custom
[HeldType](http://www.boost.org/doc/libs/1_58_0/libs/python/doc/v2/class.html#HeldType)
when exposing the legacy types to Boost.Python. When exposing the type, the
default Boost.Python generated initializers need to be suppressed, as a custom
factory function will be used instead to provide control over object creation:
/// @brief legacy_object_holder is a smart pointer that will hold
/// legacy types and help guarantee the legacy API is initialized
/// while these objects are alive. This smart pointer will remain
/// transparent to the legacy library and the user-facing Python.
template <typename T>
class legacy_object_holder
{
public:
typedef T element_type;
template <typename... Args>
legacy_object_holder(Args&&... args)
: legacy_guard_(::get_api_guard()),
ptr_(std::make_shared<T>(std::forward<Args>(args)...))
{}
legacy_object_holder(legacy_object_holder& rhs) = default;
element_type* get() const { return ptr_.get(); }
private:
// Order of declaration is critical here. The guard should be
// allocated first, then the element. This allows for the
// element to be destroyed first, followed by the guard.
std::shared_ptr<legacy_api_guard> legacy_guard_;
std::shared_ptr<element_type> ptr_;
};
/// @brief Helper function used to extract the pointed to object from
/// an object_holder. Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const legacy_object_holder<T>& holder)
{
return holder.get();
}
/// Auxiliary function to make exposing legacy objects easier.
template <typename T, typename ...Args>
legacy_object_holder<T>* make_legacy_object(Args&&... args)
{
return new legacy_object_holder<T>(std::forward<Args>(args)...);
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<
legacy::Test, legacy_object_holder<legacy::Test>,
boost::noncopyable>("Test", python::no_init)
.def("__init__", python::make_constructor(
&make_legacy_object<legacy::Test>))
;
}
* * *
Here is a complete example [demonstrating](http://coliru.stacked-
crooked.com/a/01389d3c0e229d55) using a custom HeldType to non-intrusively
lazily guard a resource with shared management:
#include <iostream> // std::cout, std::endl
#include <memory> // std::shared_ptr, std::weak_ptr
#include <boost/python.hpp>
/// @brief legacy namespace that cannot be changed.
namespace legacy {
void initialize() { std::cout << "legacy::initialize()" << std::endl; }
void shutdown() { std::cout << "legacy::shutdown()" << std::endl; }
class Test
{
public:
Test() { std::cout << "legacy::Test::Test()" << std::endl; }
virtual ~Test() { std::cout << "legacy::Test::~Test()" << std::endl; }
};
void use_test(Test&) {}
} // namespace legacy
namespace {
/// @brief Guard that will initialize or shutdown the legacy API.
struct legacy_api_guard
{
legacy_api_guard() { legacy::initialize(); }
~legacy_api_guard() { legacy::shutdown(); }
};
/// @brief Global shared guard for the legacy API.
std::weak_ptr<legacy_api_guard> legacy_api_guard_;
/// @brief Get (or create) guard for legacy API.
std::shared_ptr<legacy_api_guard> get_api_guard()
{
auto shared = legacy_api_guard_.lock();
if (!shared)
{
shared = std::make_shared<legacy_api_guard>();
legacy_api_guard_ = shared;
}
return shared;
}
} // namespace
/// @brief legacy_object_holder is a smart pointer that will hold
/// legacy types and help guarantee the legacy API is initialized
/// while these objects are alive. This smart pointer will remain
/// transparent to the legacy library and the user-facing Python.
template <typename T>
class legacy_object_holder
{
public:
typedef T element_type;
template <typename... Args>
legacy_object_holder(Args&&... args)
: legacy_guard_(::get_api_guard()),
ptr_(std::make_shared<T>(std::forward<Args>(args)...))
{}
legacy_object_holder(legacy_object_holder& rhs) = default;
element_type* get() const { return ptr_.get(); }
private:
// Order of declaration is critical here. The guard should be
// allocated first, then the element. This allows for the
// element to be destroyed first, followed by the guard.
std::shared_ptr<legacy_api_guard> legacy_guard_;
std::shared_ptr<element_type> ptr_;
};
/// @brief Helper function used to extract the pointed to object from
/// an object_holder. Boost.Python will use this through ADL.
template <typename T>
T* get_pointer(const legacy_object_holder<T>& holder)
{
return holder.get();
}
/// Auxiliary function to make exposing legacy objects easier.
template <typename T, typename ...Args>
legacy_object_holder<T>* make_legacy_object(Args&&... args)
{
return new legacy_object_holder<T>(std::forward<Args>(args)...);
}
// Wrap the legacy::use_test function, passing the managed object.
void legacy_use_test_wrap(legacy_object_holder<legacy::Test>& holder)
{
return legacy::use_test(*holder.get());
}
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<
legacy::Test, legacy_object_holder<legacy::Test>,
boost::noncopyable>("Test", python::no_init)
.def("__init__", python::make_constructor(
&make_legacy_object<legacy::Test>))
;
python::def("use_test", &legacy_use_test_wrap);
}
Interactive usage:
>>> import example
>>> test1 = example.Test()
legacy::initialize()
legacy::Test::Test()
>>> test2 = example.Test()
legacy::Test::Test()
>>> test1 = None
legacy::Test::~Test()
>>> example.use_test(test2)
>>> exit()
legacy::Test::~Test()
legacy::shutdown()
* * *
Note that the basic overall approach is also applicable to a non-lazy
solution, where the legacy API gets initialized upon importing the module. One
would need to use a `shared_ptr` instead of a `weak_ptr`, and register a
cleanup function with `atexit.register()`:
/// @brief Global shared guard for the legacy API.
std::shared_ptr<legacy_api_guard> legacy_api_guard_;
/// @brief Get (or create) guard for legacy API.
std::shared_ptr<legacy_api_guard> get_api_guard()
{
if (!legacy_api_guard_)
{
legacy_api_guard_ = std::make_shared<legacy_api_guard>();
}
return legacy_api_guard_;
}
void release_guard()
{
legacy_api_guard_.reset();
}
...
BOOST_PYTHON_MODULE(example)
{
// Boost.Python may throw an exception, so try/catch around
// it to initialize and shutdown legacy API on failure.
namespace python = boost::python;
try
{
::get_api_guard(); // Initialize.
...
// Register a cleanup function to run at exit.
python::import("atexit").attr("register")(
python::make_function(&::release_guard)
);
}
// If an exception is thrown, perform cleanup and re-throw.
catch (const python::error_already_set&)
{
::release_guard();
throw;
}
}
See [here](http://coliru.stacked-crooked.com/a/589af70587f62042) for a
demonstration.
|
Connect to SQLite3 server using PyODBC, Python
Question: I'm trying to test a class that loads data from an SQL server given a query.
To do this, I was instructed to use `sqlite3`. Now, the problem is that while
the class manages to connect to the real database with ease, I'm struggling to
connect with the temporary `sqlite3` server that I create, as I cannot figure
out what the connection string should look like. I'm using `pyodbc` in the
class to connect with databases. So, has anyone got an idea on what the
connection string should look like?
The class looks as follows:
import petl as etl
import pyodbc
class Loader:
"""
This is a class from which one can load data from an SQL server.
"""
def __init__(self, connection_string):
"""
This is the initialization file, and it requires the connection_string.
:param connection_string:
:type connection_string: str
:return:
"""
self.connection = pyodbc.connect(connection_string)
def loadFromSQL(self, query):
"""
This function loads the data according to the query passed in query.
:param query:
:type query: str
"""
self.originalTableETL = etl.fromdb(self.connection, query)
self.originalTablePD = etl.todataframe(self.originalTableETL)
And the temporary `sqlite3` server is as follows
import sqlite3 as lite
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS test_table")
cur.execute("CREATE TABLE test_table(col1 TEXT, col2 TEXT)")
cur.execute("INSERT INTO test_table VALUES('Hello', 'world!')")
So, what I wish to input is something like
tester = Loader('connection_string_goes_here')
tester.loadFromSQL("SELECT * FROM test_table")
**EDIT**
Okay, I've scoured the web a bit and found that a possible connection string
is `"DRIVER={SQL
Server};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"`. However,
the connection times out after a while and returns the following error
message:
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect)')
Which I found strange as it's local and as I haven't specified any password.
I've also tried specifying the exact path name to no avail.
Best,
Victor
Answer: Solved the problem! Downloaded an ODCB driver for `sqlite3` from
<http://www.ch-werner.de/sqliteodbc/>, and defined the connection string such
as
"DRIVER={SQLite3 ODBC Driver};SERVER=localhost;DATABASE=test.db;Trusted_connection=yes"
And it worked, hope this helps people!
|
Python Decoding with Errors=Replace
Question: Using Python 2.7, I'm grabbing some HTML from a website as strings and
immediately decoding it into unicode. Because I need to know later where any
decoding errors occurred, I thought it would be best to use errors="replace"
to prevent exceptions from non-ASCII characters:
linkname = curlinkname.decode("utf-8", errors="replace")
In most cases, this replaces the problem character with a placeholder.
However, when I run the code I am still getting an exception from this line on
one particular character (ū):
UnicodeEncodeError: 'charmap' codec can't encode character u'\u016b' in position 1: character maps to <undefined>
What's going on?
Answer: you need to install the lib first
pip install chardet
then use it
import chardet
code = chardet.detect(curlinkname)
linkname = curlinkname.decode(code['encoding'], errors="replace")
|
Need to reorder list and make a sentence in python
Question: I need help rearranging this list alphabetically
list= ['z', 'a', 'b', 'y', 'c', 'x', 'd', 'w', 'e', 'v', 'f', 'g', 'u', 'h', 'i', 'j', 't' ,'k', 'l', 's', 'm', 'n', 'r', 'o', 'p', 'q', ' ']
into "hello world" by indexing into the array. How exactly do I do that? I'm a
beginner and I'm doing this in python 2.7.
Answer: As has been mentioned, your list can be sorted alphabetically by using the
sort() function as follows:
mylist = ['z', 'a', 'b', 'y', 'c', 'x', 'd', 'w', 'e', 'v', 'f', 'g', 'u', 'h', 'i', 'j', 't' ,'k', 'l', 's', 'm', 'n', 'r', 'o', 'p', 'q', ' ']
mylist.sort()
print mylist
Which results in your list looking like:
[' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
But you go on to say 'index into' for 'hello world'. If you mean you want to
create a simple cypher then this could be easily be achieved as follows:
import string
s_from = 'abcdefghijklmnopqrstuvwxyz '
s_to = 'zabycxdwevfguhijtklsmnropq '
cypher_table = string.maketrans(s_from, s_to)
print "hello world".translate(cypher_table)
This would convert your text as follows:
wcggi rikgy
Please could you edit your question to give an example of what you are trying
to achieve.
|
trying to print a group from a regex match in python
Question: am trying to print the group info from my regex match match. My script matches
my regex versus line in my file, so that's working.
I have based this on the python regex tutorial btw ... I'm a python newbie
(with some perl experience) :)
import re
file = open('read.txt', 'r')
p = re.compile("""
.*,\\\"
(.*) # use grouping here with brackets so we can fetch value with group later on
\\\"
""", re.VERBOSE)
i = 0
for line in file:
if p.match(line):
print p.group() #this is the problematic group line
i += 1
Answer: `re.match()` returns a match object - you need to assign it to something. Try
for line in file:
m = p.match(line)
if m:
print m.group()
i += 1
|
Your WSGIPath refers to a file that does not exist
Question: I'm trying to upload my Flask application to AWS however I receive an error on
doing so:
> Your WSGIPath refers to a file that does not exist.
After doing some digging online I found that in the .ebextensions folder, I
should specify the path. There was not a .ebextensions folder so I created one
and added the following code to a file named settings.config:
option_settings:
"aws:elasticbeanstalk:container:python":
WSGIPath: project/application.py
the WSGIPath is the correct path to the application.py file so I'm not sure
what raises this error. Am I changing the WSGIPath right, is there a better
way or is there an issue with something else which causes this to happen?
Thanks.
Answer: There's a lot of configuration issues that can arise with Flask deployed on
AWS. I was running into a similar issue as you, so I can at least show you
what I did to resolve the WSGI error.
First, apparently you can do this without the .ebextensions folder (see this
post [here](http://stackoverflow.com/questions/20558747/how-to-deploy-
structured-flask-app-on-aws-elastic-beanstalk). and look at davetw12's answer.
However, be aware that while this works, I'm not entirely sure that davetw12's
conclusion about .ebextensions is correct, based on some of the comments
below). Instead, (in the Terminal), I navigated to my project at the same
level as my .elasticbeanstalk directory and used the command `eb config`. This
will open up a list of options you can set to configure your beanstalk
application. Go down through the options until you find the WSGI path. I
notice you have yours set to `project/application.py`, however, this should
not include the folder reference, just `application.py`. Here is how it looks
on my Mac in the terminal (WSGI path is near the bottom).

Note that once you get that set, EB will probably redeploy. That's fine. Let
it.
Once you get that set, go into your application.py file and make sure you call
your app `application`. For example, mine looks like this:
from flask import Flask
from flask import render_template
application = Flask(__name__)
@application.route('/')
@application.route('/index')
def index():
return render_template('index.html',
title='Home')
This took away the WSGI path error - although I still had to fix some other
issues following this :-) But that is a different set of questions.
|
python logging not saving to file
Question: I have been stuck on this for the past hour. I had plugged logging into my
tkinter gui, but could not get it to work. I then started removing parts until
I got at the bare bones example in the very python docs and it will not work.
At this point I have nothing else to remove.
The code is as follows:
import logging
LOG_FILENAME = r'logging_example.out'
logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
f = open(LOG_FILENAME, 'rt')
try:
body = f.read()
finally:
f.close()
print('FILE:')
print (body)
The warning is printed to stdout, but the file is not generated. I am runing
python 3.4, x64 on a windows 7. It is a anacondas distribution, so this is
running in Ipython inside spyder.
I guess this should be working
Answer: As Jonas Byström noted, this does work outside Ipython. It seems that Ipython
configures a logging handler before I get the chance to do so. Also,
`basicConfig` will do nothing if a handler is already present. So, in order to
have it working in Ipython, one must do one of three things: 1) Add a new
handler, OR 2)reload logging, OR 3) remove existing handlers. I did number 2
bellow.
import logging
from imp import reload
reload(logging)
LOG_FILENAME = r'logging_example.out'
logging.basicConfig(filename=LOG_FILENAME ,level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
f = open(LOG_FILENAME, 'rt')
try:
body = f.read()
finally:
f.close()
print('FILE:')
print (body)
See theese for more information: [Logging in
ipython](http://stackoverflow.com/questions/18786912/get-output-from-the-
logging-module-in-ipython-notebook); [More on the
same](http://stackoverflow.com/questions/18786912/get-output-from-the-logging-
module-in-ipython-notebook)
|
Disable pagination on the command line
Question: I am trying to write a script using the python module `pexpect` that will
connect to a server and execute commands like you are typing at the command
line.
So for example, you can have something like:
`child = pexpect.spawn('/usr/bin/ssh [email protected]')`
`child.sendLine('ls -al')`
or whatever command you want to send. It will act like you are typing in a
terminal.
In my script, I am trying to run a command using the `sendLine()` API that
essentially dumps out a bunch of info to the command line. But there is a
pagination that requires there to be another command where you have to press a
key to continue to get to the next command.
So for example:
`[Some info]`
`--------------- To continue, press any key. To quit, press 'q'.
---------------`
`[Some more info]`
Is there a way that I can turn pagination off or a command I can send before I
try to dump the info to the command line to turn it off?
Answer: **In Linux:** You can use redirection to skip the pager(`more` or `less`). If
it is important to display the output on screen, the output can be redirected
to `tee`.
For example in `man ls; ls`, the `man` command expects the user to press `q` for termination and then `ls` is executed. To execute both the commands simultaneously without user intervention, it can be done as `man ls | tee; ls`. If displaying the output is not mandatory, it can be redirected to `/dev/null` as well.
For additional help, please specify the exact command that you are trying to
execute on the remote server.
**In Python:** When using `pexpect`, the user activity can be automated if the
intermediate output is known in advance. You can use `expect` function to wait
for a particular output and then take necessary action(for example using
`sendLine`).
|
python Tkinter bind 2.7.9 w-d
Question: Hello I am having problems binding w+d in my code. I see how to do it with
Ctrl+/ and stuff like that but is it different to use two letters? I have
tried to do it a few different way here is the line i use.
root.bind('w-d',lambda x: upleftc())
Answer: It's a bit unclear what you're trying to accomplish, but if you're trying to
bind to the combination of the letter "w" followed by the letter "d", you
would bind to the two-event sequence `"<w><d>"`, or more simply, `"wd"`.
For the definitive documentation on how to specify events, see the section
["Event Patterns" in the official tcl/tk
documentation](http://tcl.tk/man/tcl8.5/TkCmd/bind.htm#M5).
Here is an example:
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.entry = tk.Entry(self)
self.entry.pack(fill="x")
self.entry.bind("<w><d>", self.onWD)
# alternatively: self.entry.bind("wd", self.onWD)
def onWD(self, event):
print "boom!"
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
|
How can I get python3.4 to find the PySDL2 module I downloaded on win7?
Question: I downloaded pySDL2 (from <https://bitbucket.org/marcusva/py-sdl2/downloads>)
and unzipped the SDL2 package to my folder C:\Python34\Lib\site-
packages\PySDL2-0.9.3, which has a subfolder sdl2 which has a subfolder ext.
I also copied a 'hello world' program to the same folder, using the header:
import os
os.environ["PYSDL2_DLL_PATH"] = "/Python34/Lib/site-packages/PySDL2-0.9.3"
import sys
import sdl2.ext
I ran it from the same folder, and It said it couldn't find sdl2. (I used the
os.environ line, since I had already 'set' the environment variable, but it
didn't help)
ImportError: could not find any library for SDL2 (PYSDL2_DLL_PATH:
/Python34/Lib /site-packages/PySDL2-0.9.3/sdl2)
So I ran pip install PySDL2, and that said: C:\Python34\Lib\site-
packages\PySDL2-0.9.3>pip install pysdl2 Requirement already satisfied (use
--upgrade to upgrade): pysdl2 in c:\python34\ lib\site-packages Cleaning up...
So, I have the package in the python library, I have it pointed to in the
environment, and pip says its already there, but somehow python can't find it
to import.
What should I be doing?
Answer: PySDL2 doesn't come with the SDL2 libraries.
You need the SDL2 libraries for PySDL2 to work. SDL2 is the library that does
all the hard work. PySDL2 is just the interface to allow you to access it from
Python.
Have a look at <http://pysdl2.readthedocs.org/en/latest/install.html> for
details about how to install it. And then look at
<http://pysdl2.readthedocs.org/en/latest/integration.html> for information
about how to use PYSDL2_DLL_PATH
For my projects I chose not to install PySDL2 in Python at all. I put all the
PySDL2 stuff in a project subdirectory called "sdl2", and all the Windows SDL2
DLLs in a separate subdirectory called "sdl2_dll". Then in the root directory
of the project I have the following file called sdlimport.py
"""Imports PySDL2
This module imports PySDL2 and the SDL2 libraries held within the project
structure (i.e. not installed in Python or in the system).
Setup:
[myproject]
|-sdlimport.py
|-main.py
|-[sdl2]
| |-The PySDL2 files
|-[sdl2_dll]
|-SDL2.dll
|-SDL2_image.dll
|-SDL2_mixer.dll
|-SDL2_ttf.dll
|-and all the other dlls needed
Edit sdlimport.py to include which bits of sdl2 you need.
Example:
from sdlimport import *
sdl2.dostuff()
"""
import os
# app_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..")
app_dir = os.path.dirname(os.path.realpath(__file__))
"""str: the path to your project, detected at import time
"""
sdl2_dll_path = os.path.join(app_dir, "sdl2_dll")
os.environ["PYSDL2_DLL_PATH"] = sdl2_dll_path
#--- Comment these out as needed ---
import sdl2
import sdl2.sdlimage
import sdl2.sdlttf
#import sdl2.sdlgfx
#import sdl2.sdlmixer
import sdl2.ext
Then, in each file that needs pysdl2, use `from sdlimport import *`
|
gdal_merge.py not working after gdal and it python bindings have been installed
Question: I installed Python 3.4.0 64 bit and gdal file
release-1400-x64-gdal-1-11-1-mapserver-6-4-1.zip from
<http://www.gisinternals.com/release.php>. I found the binding from
<http://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal> and the filename is
GDAL-1.11.2-cp34-none-win_amd64. I successfully install these files and import
gdal. However, when I run the following command within the Python IDE to merge
files 1 2 and 3, I got an error
>>> gdal_merge.py -o out.tif 1.tif 2.tif 3.tif
File "<console>", line 1
gdal_merge.py -o out.tif 1.tif 2.tif 3.tif
^
SyntaxError: invalid syntax
I specifically check to see if I can import gdal_merge as below
>>> import gdal_merge
and it was ok. I appreciate if anybody could help with this issue.
Answer: `gdal_merge.py` is part of the [GDAL
utilities](http://www.gdal.org/gdal_utilities.html) which are executed from
the command line, not from within a Python IDE or another Python script.
Just open a command line (`cmd`) and type:
python gdal_merge.py -o out.tif 1.tif 2.tif 3.tif
Depending on your environment variables and whether you included GDAL in your
Path variable you might need to specificy the full path to `gdal_merge.py`
and/or can leave out `python` at the beginning of the call.
|
passing selenium response url to scrapy
Question: I am learning Python and am trying to scrape this
[page](http://www.cppcc.gov.cn/CMS/icms/project1/cppcc/wylibary/wjWeiYuanList.jsp)
for a specific value on the dropdown menu. After that I need to click each
item on the resulted table to retrieve the specific information. I am able to
select the item and retrieve the information on the webdriver. But I do not
know how to pass the response url to the crawlspider.
driver = webdriver.Firefox()
driver.get('http://www.cppcc.gov.cn/CMS/icms/project1/cppcc/wylibary/wjWeiYuanList.jsp')
more_btn = WebDriverWait(driver, 20).until(
EC.visibility_of_element_located((By.ID, '_button_select'))
)
more_btn.click()
## select specific value from the dropdown
driver.find_element_by_css_selector("select#tabJcwyxt_jiebie > option[value='teyaoxgrs']").click()
driver.find_element_by_css_selector("select#tabJcwyxt_jieci > option[value='d11jie']").click()
search2 = driver.find_element_by_class_name('input_a2')
search2.click()
time.sleep(5)
## convert html to "nice format"
text_html=driver.page_source.encode('utf-8')
html_str=str(text_html)
## this is a hack that initiates a "TextResponse" object (taken from the Scrapy module)
resp_for_scrapy=TextResponse('none',200,{},html_str,[],None)
## convert html to "nice format"
text_html=driver.page_source.encode('utf-8')
html_str=str(text_html)
resp_for_scrapy=TextResponse('none',200,{},html_str,[],None)
So this is where I am stuck. I was able to query using the above code. But How
can I pass **resp_for_scrapy** to the **crawlspider**? I put
**resp_for_scrapy** in place of **item** but that didn't work.
## spider
class ProfileSpider(CrawlSpider):
name = 'pccprofile2'
allowed_domains = ['cppcc.gov.cn']
start_urls = ['http://www.cppcc.gov.cn/CMS/icms/project1/cppcc/wylibary/wjWeiYuanList.jsp']
def parse(self, resp_for_scrapy):
hxs = HtmlXPathSelector(resp_for_scrapy)
for post in resp_for_scrapy.xpath('//div[@class="table"]//ul//li'):
items = []
item = Ppcprofile2Item()
item ["name"] = hxs.select("//h1/text()").extract()
item ["title"] = hxs.select("//div[@id='contentbody']//tr//td//text()").extract()
items.append(item)
##click next page
while True:
next = self.driver.findElement(By.linkText("下一页"))
try:
next.click()
except:
break
return(items)
Any suggestions would be greatly appreciated!!!!
**EDITS** I included a middleware class to select from the dropdown before the
spider class. But now there is no error and no result.
class JSMiddleware(object):
def process_request(self, request, spider):
driver = webdriver.PhantomJS()
driver.get('http://www.cppcc.gov.cn/CMS/icms/project1/cppcc/wylibary/wjWeiYuanList.jsp')
# select from the dropdown
more_btn = WebDriverWait(driver, 20).until(
EC.visibility_of_element_located((By.ID, '_button_select'))
)
more_btn.click()
driver.find_element_by_css_selector("select#tabJcwyxt_jiebie > option[value='teyaoxgrs']").click()
driver.find_element_by_css_selector("select#tabJcwyxt_jieci > option[value='d11jie']").click()
search2 = driver.find_element_by_class_name('input_a2')
search2.click()
time.sleep(5)
#get the response
body = driver.page_source
return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
class ProfileSpider(CrawlSpider):
name = 'pccprofile2'
rules = [Rule(SgmlLinkExtractor(allow=(),restrict_xpaths=("//div[@class='table']")), callback='parse_item')]
def parse_item(self, response):
hxs = HtmlXPathSelector(response)
items = []
item = Ppcprofile2Item()
item ["name"] = hxs.select("//h1/text()").extract()
item ["title"] = hxs.select("//div[@id='contentbody']//tr//td//text()").extract()
items.append(item)
#click next page
while True:
next = response.findElement(By.linkText("下一页"))
try:
next.click()
except:
break
return(items)
Answer: Use [Downloader Middleware](http://doc.scrapy.org/en/latest/topics/downloader-
middleware.html) to catch selenium-required pages _before_ you process them
regularly with Scrapy:
> The downloader middleware is a framework of hooks into Scrapy’s
> request/response processing. It’s a light, low-level system for globally
> altering Scrapy’s requests and responses.
Here's a very basic example using PhantomJS:
from scrapy.http import HtmlResponse
from selenium import webdriver
class JSMiddleware(object):
def process_request(self, request, spider):
driver = webdriver.PhantomJS()
driver.get(request.url)
body = driver.page_source
return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
Once you return that `HtmlResponse` (or a `TextResponse` if that's what you
really want), Scrapy will cease processing downloaders and drop into the
spider's `parse` method:
> If it returns a Response object, Scrapy won’t bother calling any other
> process_request() or process_exception() methods, or the appropriate
> download function; it’ll return that response. The process_response()
> methods of installed middleware is always called on every response.
In this case, you can continue to use your spider's `parse` method as you
normally would with HTML, except that the JS on the page has already been
executed.
**Tip: Since the Downloader Middleware's`process_request` method accepts the
spider as an argument, you can add a conditional in the spider to check
whether you need to process JS at all, and that will let you handle both JS
and non-JS pages with the exact same spider class.**
|
Python regex : detect a word with duplicated chars
Question: I wonder if i could detect the word '**hey** ' but in this form : '**heeeey**
' How would i do that in python ? I searched many times but i didn't find an
answer.
*I want the program to get it like 'hey' at last, i want it to understand that 'heeey' means 'hey'.
Answer:
import re
p = re.compile(r'(.)\1+')
test_str = "heeeey"
subst = r"\1"
result = re.sub(p, subst, test_str)
You can do it through `re.sub`.Here we capture any `character` which are
repeated ahead and replace all by `\1` .So all the repetitions will be gone.
See demo.
<https://regex101.com/r/cK4iV0/7#python>
|
Simple explanation of security issues related to input() vs raw_input()
Question: I was reading this Python 2.7 tutorial and they're going over `raw_input()`,
and it mentions that:
> The input() function will try to convert things you enter as if they were
> Python code, but it has security problems so you should avoid it.
I tried Googling some explanations for this, but still a bit unclear to me;
what's a simple explanation of the alleged inherent security issues with
`input()` vs `raw_input()` ?
Answer: The `input()` function in Python 2.x evaluates things before returning.
So as an example you can take a look at this -
>>> input("Enter Something : ")
Enter Something : exit()
This would cause the program to exit (as it would evaluate exit()).
Another example -
>>> input("Enter something else :")
Enter something else :__import__("os").listdir('.')
['.gtkrc-1.2-gnome2', ...]
This would list out the contents of current directory , you can also use
functions such as `os.chdir()` , `os.remove()` , `os.removedirs()` ,
`os.rmdir()`
|
How do I find duplicates within two columns in a csv file, then combine them in Python?
Question: I am working with a large dataset of protein-protein interactions, which I
have in a .csv file. The first two columns are the interacting proteins, and
the order does not matter (ie A/B is the same as B/A, so they are duplicates).
There is also a third column, with a source for where these interactions were
published. Duplicate pairs can be from the same source, or different sources.
For the duplicates that are from two or more sources, how can I combine them,
then in the third column have all of the sources listed for one interaction?
(i.e. for an interaction A/B, the duplicates would be A/B and B/A).
Here is an example of the columns:
Interactor A Interactor B Source
A B Mary (2005)
C D John (2004)
B A Mary (2005)
A B Steve (1993)
D C Steve (1993)
In this case, i would need
Interactor A Interactor B Source
A B Mary (2005), Steve (1993)
C D John (2004), Steve (1993)
Thanks!
Answer: You could aggregate them using the **sorted** `tuple` as a dictionary key (to
make `A, B` and `B, A` equivalent, tuples can be used as a dictionary key,
since it's immutable and hashable - lists are not) . Use a
[`set`](https://docs.python.org/2.7/library/stdtypes.html#set) to store the
aggregated values and avoid duplicates.
I'd also throw in
[`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict)
to make it nicer to aggregate values:
from collections import defaultdict
import csv
# ... read values using a csv reader (assuming name csv_reader)
result = defaultdict(set)
for row in csv_reader:
# create same key for `A, B` and `B, A`
key = tuple(sorted([row[0], row[1]]))
result[key].add(row[2])
# result should now contain all aggregated values
|
Deleting all files in a folder in Python
Question: I am trying to make a program in Python that will delete all files in the
`%temp%` path, also known as `C:\Users\User\AppData\Local\Temp`.
How can I do this? I am using Python 3.4.
Answer: In general, you could use
[`shutil.rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree)
to delete all files/directories in a folder:
#!/usr/bin/env python
import shutil
import tempfile
dirpath = tempfile.mkdtemp()
try:
# use the temporary directory here
...
finally:
shutil.rmtree(dirpath) # clean up
The above can be written simpler if it is all you need (create a temporary
directory from scratch):
#!/usr/bin/env python3
import tempfile
with tempfile.TemporaryDirectory() as dir:
print(dir.name) # use the temporary directory here
|
Can we pass the captured packets as argument to Socket send() function
Question: I'm beginner to Networking. We have sender and receiver application. I have
captured the packets sent by sender to receiver using WinDump.
I'm writing a python sender application which will fuzz the packets sent by
sender to receiver.
I just want to confirm, can I directly put the packet data obtained using
WinDump to socket send() method.
Say, "arp who-has host1 tell host2" is the packet obtained by WinDump
Can I write,
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(arp who-has host1 tell host2)
Answer: In general pyhton network programming you can not pass as the arguments using
send method.you just only pass the string as arguments as variable.
Basically we are using the send() and sendall() method to transmits the TCP
messages.
I have mentioned the below desciption for both the method.
**socket send() method :**
The socket's `send()` method is not guaranteed to send all of the data you
pass it. Instead, it returns the number of bytes that were actually sent and
expects your application to handle retransmission of the unsent portion
from socket import socket
sock = socket()
sock.connect(('1.2.3.4', 1234))
sock.send('My Name is Dasadiya Chaitanya !!!\n'')
sock.close()
**socket sendall() method :**
which is same work as the `send()` method but python provides a convenience
method called `sendall()` that makes sure all of your data is sent before
returning and also provide the guarantee to send all the data to the receiver.
from socket import socket
sock = socket()
sock.connect(('1.2.3.4', 1234))
sock.sendall('My Name is Dasadiya Chaitanya !!!\n')
sock.close()
I hope this should helpful for you :)
|
Why does the following mouse click code results in Windows error 997?
Question: I am doing a mini project where a switch press results in a mouse click or in
other words the switch acts as an alternative to my left mouse button.
My code is
import pyautogui , time , serial
port = serial.Serial('COM3',9600)
flag=0
while 1:
reading=port.read()
x=ord(reading)
if x==1 and flag==0:
flag=1
pyautogui.mouseDown()
elif x==2:
flag=0
pyautogui.mouseUp()
The serial transmission is such that it receives a
> 0 - Switch not pressed
> 1 - Switch pressed
> 2 - switch just left
A 2 is always transmitted in between a 1 and a 0.
My problem is that when I run this code the following error occurs after one
mouse click.
> Traceback (most recent call last):
>
> File "C:\Python27\LeftClick.py", line 12, in pyautogui.mouseUp()
>
> File "C:\Python27\lib\site-packages\pyautogui__init__.py", line 234, in
> mouseUp
>
> platformModule._mouseUp(x, y, 'left')
>
> File "C:\Python27\lib\site-packages\pyautogui_pyautogui_win.py", line 415,
> in _mouseUp
>
> _sendMouseEvent(MOUSEEVENTF_LEFTUP, x, y)
>
> File "C:\Python27\lib\site-packages\pyautogui_pyautogui_win.py", line 480,
> in _sendMouseEvent raise ctypes.WinError()
>
> WindowsError: [Error 997] Overlapped I/O operation is in progress.
Answer: In the comments above, you say that if you take serial out, the program works
as expected, if I read it correctly. You also say that mouse movement works OK
on COM3, but if removing the serial comms fixes the issue, then I'd say that's
a fairly strong indication that COM3 may be the culprit, it should certainly
be investigated.
My suggestion: Use a different COM port for your serial device. You can change
the number used by going into:
`Device Manager > Ports (COM & LPT) > Right Click your device > Properties >
Port Settings > Advanced > COM Port Number`
|
Python Encoding Issues
Question: I have data that I would like to decode from and its in Windows-1252 basically
I send code to a socket and it sends it back and I have to decode the message
and use IEEE-754 to get a certain value from it but I can seem to figure out
all this encoding stuff. Here is my code.
def printKinds ():
test = "x40\x39\x19\x99\x99\x99\x99\x9A"
print (byt1Hex(test))
test = byt1Hex(test).replace(' ', '')
struct.unpack('<d', binascii.unhexlify(test))
print (test)
printKinds()
def byt1Hex( bytStr ):
return ' '.join( [ "%02X" % ord( x ) for x in bytStr ] )
So I use that and then I have to get the value from that.. But it's not
working and I can not figure out why.
The current output I am getting is
struct.unpack('<d', binascii.unhexlify(data))
struct.error: unpack requires a bytes object of length 8
That the error the expected output I am looking for is **25.1** but when I
encode it, It actually changes the string into the wrong values so when I do
this:
print (byt1Hex(data))
I expect to get this.
40 39 19 99 99 99 99 9A
But I actually get this instead
78 34 30 39 19 99 99 99 99 9A
Answer:
>>> import struct
>>> struct.pack('!d', 25.1)
b'@9\x19\x99\x99\x99\x99\x9a'
>>> struct.unpack('!d', _) #NOTE: no need to call byt1hex, unhexlify
(25.1,)
You send, receive bytes over the network. No need hexlify/unhexlify them;
unless the protocol requires it (you should mention the protocol in the
question then).
|
I am trying to import a set of lists in python and call a random item from one of the lists
Question:
#Set of lists I want to import into my python program called "setlist.txt"
---------------------------------------------------------------------------------------------
Tripolee = ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox')
Ranch = ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade')
Sherwood = ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume')
Jubilee = ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO')
The Hangar = ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD')
Forest = ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')
---------------------------------------------------------------------------------------------
#program
from sys import exit
from random import randint
from sys import argv
script, setlist = argv
setlist = open(setlist)
print "Here is the setlist for day 1"
print setlist.read()
print "%r is playing on the Tripolee stage" % random.choice(setlist.readline(2))
I have a bunch more code in between all this that I"m not putting up here but
basically that last line what I'm having trouble with.
Answer: Probably not the best format for your file but you can split and use
ast.literal_eval:
from ast import literal_eval
with open("in.txt") as f:
choices = [literal_eval(line.split(" = ")[-1]) for line in f]
Which will give you a list of tuples which you can pass to random.choice:
[('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox'), ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade'), ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume'), ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO'), ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD'), ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')]
I have no idea where setlist is supposed to come from, you file is what looks
like tuple assignments. `setlist.readline(2)` would read 2 bytes or actually
in your case nothing as you have already exhausted the file iterator calling
`read`.
I would suggest after extracting using literal_eval putting your file in a
more usable format, maybe creating a dict using the name as the key and
dumping the dict.
from ast import literal_eval
with open("in.txt") as f:
choices = {}
for line in f:
ven, tpl = line.split(" = ")
choices[ven] = literal_eval(tpl)
print(choices)
Output:
{'Jubilee': ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO'), 'Tripolee': ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox'), 'The Hangar': ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD'), 'Ranch': ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade'), 'Sherwood': ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume'), 'Forest': ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')}
You can persist the dict using `json.dump` or the `pickle` module so your data
will be in a lot easier format to each time.
To make it a little clearer what you have below is the content of your .txt
file:
---------------------------------------------------------------------------------------------
Tripolee = ('Saeed Younan', 'Matrixxman', 'Pete Tong', 'Dubfire', 'John Digweed', 'Carl Cox')
Ranch = ('Dabin', 'Galantis', 'Borgeous', 'Shpongle', 'ODESZA', 'Kaskade')
Sherwood = ('Nadus', 'Mr. Carmack', 'Wave Racer', 'Lido', 'Goldlink', 'Four Tet', 'Flume')
Jubilee = ('Chaz French', 'MartyParty', 'Sango', 'Brodinski', 'Phutureprimitive', 'EOTO')
The Hangar = ('Vourteque', 'The Gentlemen Callers', 'Bart&Baker', 'Jaga Jazzist', 'JPOD')
Forest = ('Vibe Street', 'Lafa Taylor', 'Vaski', 'Little People', 'jackLNDN', 'MartyParty')
To print the venue and set list you can use dict.items:
for ven, set_l in choices.items():
print("Set list for {}: {}".format(ven, ", ".join(set_l)))
Output:
Set list for Jubilee: Chaz French, MartyParty, Sango, Brodinski, Phutureprimitive, EOTO
Set list for Tripolee: Saeed Younan, Matrixxman, Pete Tong, Dubfire, John Digweed, Carl Cox
Set list for The Hangar: Vourteque, The Gentlemen Callers, Bart&Baker, Jaga Jazzist, JPOD
Set list for Ranch: Dabin, Galantis, Borgeous, Shpongle, ODESZA, Kaskade
Set list for Sherwood: Nadus, Mr. Carmack, Wave Racer, Lido, Goldlink, Four Tet, Flume
Set list for Forest: Vibe Street, Lafa Taylor, Vaski, Little People, jackLNDN, MartyParty
When you open the file and call `read` you now have all the content in your
file stored as a string. You then print the string, next you try
`random.choice(setlist.readline(2))`, `readline(2)` is trying to read two
bytes which it cannot even do as the file pointer is at the end of the file as
you have already called `read` so you see an empty string outputted.
If you want to get a random string from the first tuple:
choices = [literal_eval(line.split(" = ")[-1]) for line in f]
from random import choice
print(choice(choices[0]))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.