Menu
  • HOME
  • TAGS

How to override __str__ in nested class

python,pydev,python-3.4,nested-class

print Parent.Nested() # works fine, print calls __str__ resulting in 'Child' ...

Weird behaviour with len and str.splitlines()

python,string,typeerror,python-3.4

A friend of mine (all credits to Mariano Garcia) has helped me and as he doesn't have SO account I will post what solved this behavior, my console was enforcing utf-8 but internally the text still had to be encoded so what solved this changing this if len(r.text.splitlines()) > 1:...

Is there a Spanish to English dictionary for use with python 3? [closed]

python,dictionary,nltk,python-3.4

You don't need any dictionary specially formatted for python, just a format you can digest with python, and that would mean pretty much any well known text format. Just try to find an opensource dictionary in an easy to digest format and parse it with python. Here for example: http://www.dicts.info/uddl.php...

Pickle user inputs - Python 3 [closed]

python,pickle,python-3.4

The following runs well. Rename your Player class with an uppercase initial to avoid name conflicts. I added some test calls at the end, and the player is loaded with the intended (not default) stats. import pickle class Player: def __init__(self, hp, dmg): self.hp = hp self.dmg = dmg def...

How do i query SQlite using python and then compare the query result?

python,sqlite,sqlite3,python-3.4

cursor.fetchone() fetches a row as a tuple: passcheck == ("hashed password", ) You must compare agains passcheck[0] or unpack the tuple: passcheck, = cursor.fetchone() Edit: Let the database do the comparing: cursor.execute("SELECT * FROM users WHERE username= ? and password= ?", (username, pass1)) found = cursor.fetchone() if found: # user...

How to run selenium tests in jenkins?

unit-testing,selenium,jenkins,automated-tests,python-3.4

How to run them from jenkins after success build ? - You can add a trigger to your selenium job so it runs after the build job runs successfully To answer your question accurately, I need to know whether you are planning in running selenium tests in jenkins box... Assuming...

Inserting row into SQLite table

python,sqlite3,python-3.4

The cursor object has the last insert ID in its lastrowid attribute. cursor.execute('INSERT ...') new_id = cursor.lastrowid db.commit() return new_id ...

Lift and raise a Canvas over a Canvas in tkinter

python,python-3.x,canvas,tkinter,python-3.4

The answer is very easy: To convert to Python3, change Tkinter to tkinter, and it works! import tkinter as tk class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.frame = tk.Frame(self) self.frame.pack(side="top", fill="both", expand=True) self.label = tk.Label(self, text="Hello, world") button1 = tk.Button(self, text="Click to hide label", command=self.hide_label) button2 =...

Converting a List within a List from String to Integers

python,type-conversion,python-3.4

You can use map to convert the strings to ints. (You seem to have an extra iteration to find the number of participants which can be counted during the first loop) def cond1_a(): c1resplist=[] participants=0 with open("condition1.txt","r") as f: for line in f: c1resplist.append(list(map(int, line.split()))) participants+=1 return c1resplist, participants print(cond1_a())...

VIM: Use python3 interpreter in python-mode

python,vim,ubuntu-14.04,python-3.4,python-mode

Try adding this to your .vimrc file let g:pymode_python = 'python3' I found this in the help docs. In vim type: :help python-mode By default, vim is not compiled with python3 support, so when I tried this, I got all kinds of errors... Which tells me it's trying to use...

Save user input from tkinter to a variable and check its content

python,input,tkinter,python-3.4

The simplest solution is to make string global: def printtext(): global e global string string = e.get() text.insert(INSERT, string) When you do that, other parts of your code can now access the value in string. This isn't the best solution, because excessive use of global variables makes a program hard...

How To Achieve Python3.4 Virtualenv For Precise64 VirtualBox

django,virtual-machine,ubuntu-12.04,ansible,python-3.4

Edit this two file System packages After line26 add - python3-dev - python3-setuptools to get python3-dev and python3-setuptools packages. Virtualenv Replace 4th line with command: virtualenv {{ virtualenv_path }} --no-site-packages -p /usr/bin/python3 to instruct virtualenv to use python3 Please note youtube-audio-dl is not compatible with python3. You may use any...

How to set the inline image opaque in QtConsole3?

python,python-3.4,qtconsole

You could change your rcparams programatically before plotting matplotlib.rcParams['figure.facecolor'] = "(1, 1, 1)" or in your matplotlibrc file; or you could be explicit: fig = figure(facecolor='w') ax = fig.add_subplot(111) ax.plot(x, y) fig ...

Is there a PyMOD(DEINIT)_FUNC?

python,python-3.4,python-c-extension

Python 2 does not support module finalisation, no. See bug 9072: Please accept that Python indeed does not support unloading modules for severe, fundamental, insurmountable, technical problems, in 2.x. For Python 3, the C API for module initialisation was overhauled (see PEP 3121) and the new PyModuleDef struct has a...

how to tell python 3 to skip over non-digit characters from a csv file

python,csv,replace,python-3.4

if the strange characters are known (i.e only '?') perhaps something like this? the_numbers = [float(row[rowNum]) for row in reader if row[rowNum] not in "?"] #replace "?" with a string of any strange characters BTW, that code has something weird somewhere else: averageNum is an inmutable object: passing it as...

Python igraph for windows 64bit

python,igraph,python-3.4

Christoph Gohlke's page contains a Python wheel compiled for Python 3.4 on a 64-bit Windows machine.

Installing Ghost.py

python,installation,python-3.4,ghost.py

You need to literally call the install for Ghost.py since the module isn't named ghost through PyPi. Python2: pip install Ghost.py Python3: python3.4 -m ensurepip pip3.4 install Ghost.py Note: You may need to use sudo to install pip. Then you will be able to use Ghost: from ghost import Ghost...

Python 3.4.3 Tkinter TTK file not opening

python,tkinter,python-3.4,ttk

I can't reproduce your error, but I have an idea what's causing it. My guess is that your OS runs .pyw files using py2. You can double check this in your registry (assuming Windows). Check the following key Computer\HKEY_CLASSES_ROOT\Python.NoConFile\shell\open\command And change its default value to "C:\Python34\pythonw.exe" "%1" %* Or wherever...

Defining django models in an alphabetic order

django,python-3.x,python-3.4

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself: question = models.ForeignKey('Question') instead of question = models.ForeignKey(Question) From https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey...

Content-Length should be specified for iterable data of type class 'dict'

python,python-3.4

urllib.request does not support passing in unencoded dictionaries; if you are sending JSON data you need to encode that dictionary to JSON yourself: import json json_data = json.dumps(payload).encode('utf8') request = urllib.request.Request(url, data=payload, method='PUT', headers={'Content-Type': 'application/json'}) You may want to look at installing the requests library; it supports encoding JSON for...

does the order when defining functions in classes in python matter

python,function,class,python-3.4

The order of class attributes does not matter except in specific cases (e.g. properties when using decorator notation for the accessors). The class object itself will be instantiated once the class block has exited.

py2exe fails with “No module named 'clr'” when trying to build exe from script using pythonnet

python,dll,clr,python-3.4,python.net

Install description For reference, I performed standard install of py2exe using pip install py2exe. This puts py2exe into the Lib\site-packages for your python install. Next, I installed pythonnet by downloading the .whl from Christoph Gohlke's unofficial Windows binaries page, then using pip install path\to\pythonnet-2.0.0<version_numbers>.whl. This puts clr.pyd and Python.Runtime.dll into...

Creating matrices in Numpy?

python,numpy,python-3.4

The answer is right in the error message. You're passing five parameters to np.matrix: matrix = np.matrix((str(1), str(0), str(0), str(x)), (str(0), str(1), str(0), str(y)), (str(0), str(0), str(1), str(z)), (str(0), str(0), str(0), str(1))) np.matrix does not take five parameters. This is what you meant to do: matrix = np.matrix(((str(1), str(0), str(0),...

Python 3.4 Pandas DataFrame Structuring

pandas,dataframes,python-3.4

You can skip every other line with a slice and iloc: In [11]: df = pd.DataFrame({0: ['A', 1, 'A', 3], 1: ['B', 2, 'B', 4]}) In [12]: df Out[12]: 0 1 0 A B 1 1 2 2 A B 3 3 4 In [13]: df.iloc[1::2] Out[13]: 0 1 1...

Why is this Python 3 asyncio client sending the bytes only after the Python process is interrupted?

python,client-server,python-3.4,python-asyncio

The problem is likely that you're calling reader.read() on the server-side (and also on the client-side), which will block until an EOF is sent from the server. But presumably you're not doing that - you're just sending some bytes over and keeping the connection open. Instead, you need either to...

How to run qtconsole connected to ipython3 instance?

ipython,python-3.4,qtconsole

Reposting as an answer: If you just run ipython3 in a terminal, what you get is a pure terminal interface, it's not running a kernel that the Qt console can talk to. If you run ipython3 console, you'll get a similar interface but it will be talking to a kernel,...

Using python dict imported from file in another python file

python,dictionary,python-3.4

There are two ways you can access variable TMP_DATA_FILE in file file1.py: import file1 var = 'a' print(file1.TMP_DATA_FILE[var]) or: from file1 import TMP_DATA_FILE var = 'a' print(TMP_DATA_FILE[var]) In both cases, file1.py must be in a directory contained in the python search path, or in the same directory as the file...

how can I add text to these rectangles?

python,text,menu,pygame,python-3.4

Check out this stack overflow question: How to add text into a pygame rectangle Specifically these bits: self.font = pygame.font.SysFont('Arial', 25) def addText(self): self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100)) pygame.display.update() Basically you want to define a font Then blit it onto the screen, where render takes the args (text, antialias (you...

Setting the mac task bar menu with pyqt4 and then applying cx_freeze

python,osx,pyqt4,python-3.4,cx-freeze

I'm not really sure why this wasn't working, or why my method fixed it, but I did 2 things to prevent the menu messing up: 1. I had been loading another main window before loading this one which was a smaller setup window. I now load this only when needed....

Total Beginner: Python 3.4 spot the syntax error

python-3.4

Syntax Error: The brackets are not necessary; use the following: for x in List[0] and y in range(0, 11): ... More Problems Although as in my comment, this won't necessarily work. Merging the Arrays: If you are trying to go through all values in List[0] and then in range(0, 11),...

Creating Pascal's Triangle using Python Recursion

python,recursion,python-3.4

You are not, in fact, using recursion at all in your answer. I think you are trying to code the formula nCk = (n-1)C(k-1) + (n-1)Ck. You need, therefore, to call combination from within itself (with a guard for the "end" conditions: nC0 = nCn = 1): def combination(n, k):...

Python 3 : Why would you use urlparse/urlsplit [closed]

python-3.4,urlparse

Use urlparse only if you need parameter. I have explained below why do you need parameter for. Reference urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True) This is similar to urlparse(), but does not split the params from the URL. This should generally be used instead of urlparse() if the more recent URL syntax allowing...

Python3 csv DictWriter: writing through bz2 fails (TypeError: 'str'/buffer interface)

python,python-3.x,python-3.4

Note that the bz2.open defaults to binary mode. This is in contrast to the regular Python built-in open which defaults to text mode. To solve your error, you simply need to open the file in text mode, not the default binary mode. Change the with bz2.open(... mode='w'...) to with bz2.open(......

Python3 run os.popen with argument?

subprocess,popen,python-3.4

f1 = os.popen("python /home/shanaka/volapp/volatility-2.3.1/vol.py -f /home/shanaka/memory_sample/ubuntu-12.04-amd64-jynxkit.mem --profile="+OSselection.get().rstrip()+" "+ option.get().rstrip()) argument taking as new line, so i have remove the new line. ...

How to install requests module in python 3.4 version on windows?

pip,python-3.4

python -m pip install requests

which one is the right definition of data-descriptor and non-data descriptor?

python,python-3.4

The second quote is correct. The second quote comes from the Python language reference (though you've provided the wrong link), and the language reference is considered more authoritative than how-to guides. The language reference also explains why Set doesn't override the instance dict for a.b: If it does not define...

If statement looking for float is not working

python,python-3.4

Instead of checking type, you should just do the conversion in a try/except block. totaltime = 0.0 while True: try: new_time = float(input("How long will this task take?\n> ")) totaltime += new_time break except ValueError: print("You must enter a valid number, written as (H.M).") Your attempt to check type is...

NetworkX Graph object not subscriptable

python,python-3.x,python-3.4,networkx

Analysis of your current approach You are using subscript notation via the square brackets. Normally, you would type my_object[key], which is translated as a first approximation* into my_object.__getitem__(key). In particular, if the type(my_object) does not define the __getitem__ attribute, then you effectively get an error that says that type(my_object) is...

Tkinter self.grid making widgets invisible

python,tkinter,python-3.4

You are putting the initial frame (variable frame) in master, and you are using pack. The remaining widgets are also going in master, and you are using grid. This typically results in your program locking up because grid will try to arrange the widgets, pack will notice they've changed and...

How do you plot a graph consisting of extracted entries from a nested list?

plot,list-comprehension,python-3.4,nested-lists

You need to build two new lists. You can do this with list comprehensions: x = [sub[0] for sub in nested_list] y = [sub[2] for sub in nested_list] plt.plot(x,y) Your code tried to access one level of nesting too many (you can only address nested_list[k][0], not nested_list[k][0][0]) or tried to...

Are there memory limitations when outputting to a ScrolledText widget?

memory,logging,textbox,tkinter,python-3.4

In general, no, there are no memory limitations with writing to a scrolled text widget. Internally, the text is stored in an efficient b-tree (efficient, unless all the data is a single line, since the b-tree leaves are lines). There might be a limit of some sort, but it would...

Response Time Accuracy

python,time,python-3.4,psychopy

Python's time functions are not the limiting factor here. Depending on your particular computer and OS, you can get microsecond resolution (subject to all sorts of caveats about multitasking and so on). The real issue is hardware. There is no point worrying about millisecond time resolution if you are collecting...

urllib keeps freezing while trying to pull HTML data from a website - is my code correct?

python,osx,parsing,urllib,python-3.4

Since you mentioned requests, I think it's a great solution. import requests import BeautifulSoup r = requests.get('http://example.com') html = r.content soup = BeautifulSoup(html) table = soup.find("table", {"id": "targettable"}) As suggested by jonrsharpe, if you're concerned about the size of the response returned by that url, you can check the size...

Random's randint won't work in a for-loop

for-loop,random,python-3.4

you don't say anything about the content of the lists, supposing that they also contain random integers, then a possible solution could be the following: """ It creates a list with random length filled with lists of random lengths containing random integers """ import random MIN_LIST_OF_LISTS_LENGTH = 1 MAX_LIST_OF_LISTS_LENGTH =...

Can python file be executed in Command Prompt regardless the drive where you installed Python program?

python,command-prompt,python-3.4

Yes, you always have to tell the computer to use the python executable to execute python programs. It does not matter if you install to C: or E: drive either, you just always have to start out by specifying python executable. The program you are running is just an argument...

Can't make PyQt5 Gui work, python3

python-3.4,pyqt5

That is becuase you have ran something along the lines of: pyuic5 view.ui -o view.py Where view.ui is your Qt Designer file and view.py is your output file. The output file view.py isn't executable. If you look at the documentation, you will see that you can use another flag (-x)...

python memory usage dict and variables large dataset

python,python-3.4

You can use sys.getsizeof(object) to get the size of a Python object. However, you have to be careful when calling sys.getsizeof on containers: it only gives the size of the container, not the content -- see this recipe for an explanation of how to get the total size of a...

How can I read a reg_qword in winreg in python 3.4?

python,windows,registry,python-3.4,winreg

The code you wrote interprets the value as a big-endian-stored integer. However, REG_QWORD is stored as a little-endian number. There's a much easier way to convert the bytes value of a 64-bit integer: using struct.unpack(). The format '<q' will read a signed 64-bit little-endian integer: >>> struct.unpack('<q', b'\x10\xba\xef\xa7S\x12\x00\x00') (20150509091344,) And...

jenkins cannot run firefox: No protocol specified Error: cannot open display: :0

linux,firefox,jenkins,python-3.4

Just install a virtual framebuffer in your machine and it will work. Now i'm using Xvfb, but there are many others. Here is some tutorials to setup your machine: http://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/ http://www.labelmedia.co.uk/blog/setting-up-selenium-server-on-a-headless-jenkins-ci-build-machine.html Also, there is this plugin: https://wiki.jenkins-ci.org/display/JENKINS/Xvfb+Plugin...

AttributeError: 'module' object has no attribute 'ensuretemp'

python,python-3.4,py.test

No, you're doing everything correctly as documentation shows. I'm unable to get it working either. On other hand, pytest has fixture tmpdir, which does what you need in the test: gives you unique temporary directory for your test. Here is an example of test: def test_one(tmpdir): test_file = tmpdir.join('dir', 'file').ensure(file=True)...

Invoking an earlier version of python in cmd

windows,python-2.7,python-3.4

Update: If your system environment is Windows: 1) call py -2.7 or py -3 based on the version you want. 2) change your PATH system environment variable , makes sure it refers to the version you want. You can do it in serveral ways on Linux environment: 1) call a...

Using functions from a class in another file to a class in my second file, python3

python-3.4

You have to import the first file into the second one as import first_filename as t then create class object p=t.classname then use any function you want which is declared in the class

Connect to FTP TLS 1.2 Server with ftplib

python,ssl,ftp,python-3.4

See the end of this post for the final solution. The rest are the steps needed to debug the problem. I try to connect to a FTP Server which only supports TLS 1.2 Using Python 3.4.1 How do you know? ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:598) I would...

Backport Python 3.4's regular expression “fullmatch()” to Python 2

regex,python-3.4,python-2.x,backport

To make sure that the entire string matches, you need to use the \Z end-of-string anchor: def fullmatch(regex, string, flags=0): """Emulate python-3.4 re.fullmatch().""" return re.match("(?:" + regex + r")\Z", string, flags=flags) The \A anchor is not necessary since re.match() already anchors the match to the start of the string....

Bounce back animation difficulty with space invaders clone

python,pygame,python-3.4

A possible way to make the track for the Enemy class would be to have a default track like this: class Enemy(pygame.sprite.Sprite): path = [(0,0), (1,5), (2,11) .... ] def __init__(self, color, x, y): #adding additional x, y arguments will declutter your code super().__init__() self.x, self.y = x, y #assign...

How do I escape forward slashes in python, so that open() sees my file as a filename to write, instead of a filepath to read?

python,python-3.4

you cannot have / in the file basename on unix or windows, you could replace / with .: page.replace("/",".") + ".txt" Python presumes /site etc.. is a directory....

Python 3 Combobox issue?

combobox,tkinter,python-3.4

Thanks for the Support I found the solution , I used ttk.ComboBox, rather using Pmw. Thank you Jonrsharp option = ttk.Combobox(root,state="readonly",values=(lines))

Proper use of lambda in function definition

python,string,lambda,python-3.4

You cannot use a lambda expression to describe actions that should be performed on input parameters (you can however use lambda to define a default value). You can do two things: Define a function in the head of the function: def palindrome(s): s = s.lower() return s == s[::-1] Use...

How to convert date string to a datetime object in a specified timezone

python,datetime,python-3.x,python-3.4

This is not possible using only Python's standard library. For full flexibility, install python-dateutil and pytz and run: date_str = '2015-01-01' dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str)) This gives you a datetime with Europe/London timezone. If you only need parsing of '%Y-%m-%d' strings then you only need pytz: from datetime import datetime naive_dt...

Create an exe with Python 3.4 using cx_Freeze

python,python-3.4,cx-freeze

Since you want to convert python script to exe have a look at py2exe

Print into console terminal not into cell output of IPython Notebook

python,windows,ipython,ipython-notebook,python-3.4

You have to redirect your output to the systems standard output device. This depends on your OS. On Mac that would be: import sys sys.stdout = open('/dev/stdout', 'w') Type the above code in an IPython cell and evaluate it. Afterwards all output will show up in terminal....

python 3.4 modules can be install because numpy

numpy,python-3.4

fix with this Wheels and this files : http://www.lfd.uci.edu/~gohlke/pythonlibs/#NumPy...

What's the correct way to clean up after an interrupted event loop?

python,python-3.4,python-asyncio

When you CTRL+C, the event loop gets stopped, so your calls to t.cancel() don't actually take effect. For the tasks to be cancelled, you need to start the loop back up again. Here's how you can handle it: import asyncio @asyncio.coroutine def shleepy_time(seconds): print("Shleeping for {s} seconds...".format(s=seconds)) yield from asyncio.sleep(seconds)...

What is the preferred way to add many fields to all documents in a MongoDB collection?

mongodb,python-3.4

this is actually a great question that can be solved a few different ways depending on how you are managing your data. if you are upserting additional fields does this mean your data is appending additional fields at a later point in time with the only changes being the addition...

Can you set cwd for abspath?

python,path,python-3.4

The current solution seems clunky, is there a better way to accomplish this? You can write your own code as a context manager which changes the directory and then changes back: >>> from contextlib import contextmanager >>> @contextmanager ... def cwd(path): ... from os import getcwd, chdir ... cwd...

SQLite database query (Python, Bottle)

python,sqlite,python-3.4,bottle

See the cursor.fetchall documentation: Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available. Since an empty list in Python is a false-y expression this normally...

How to 'pipe' password to remote.update() with gitPython

python,git,python-3.4,atlassian-stash,gitpython

Instead of using http use ssh. Once you set up your ssh keys the authentication is done "silently" with the ssh keys and there will be no need to enter password ever again. Generating ssh keys: ssh-keygen -t rsa -C '[email protected]' Once you create your keys add them to the...

How can i make a startmenu in python?

python,menu,python-3.4,2d-games,startmenu

I'm assuming by "start menu" you mean what is commonly called a "toplevel menu", "application menu", or "application menu-bar". On MS-Windows, for example, this would be a menu that appears across the top of the application window. Here is a link to some good help about menus: The Tkinter Menu...

Limited traceback running python -m

python,debugging,python-3.4

If you use -m, you shouldn't specify the .py extension, since you are specificying a module name, not a file per se. See the documentation.

Python ast parsing exception

python-2.7,abstract-syntax-tree,python-3.4

Turns out it is not possible to use different versions of AST parsers in python to the best of my knowledge. (It is still possible to parse them separately by carrying out multiple iterations each time using a different version AST)

Python import doesn't work when file is imported

python,python-3.4,python-import,python-module

The error is due to the fact that python is searching for a top-level package called boxCovering inside the PYTHONPATH and none exists (you have only a sub-package inside the current directory, but this isn't searched). When you want to import a subpackage/submodule you want to use a(n explicit) relative...

Drawing pentagon,hexagon in Pygame

python,algorithm,pygame,python-3.4

You can draw it using lines. You only need to generate list of vertices with simple trygonometry. Something like this (if I didn't make a mistake): def draw_ngon(Surface, color, n, radius, position): pi2 = 2 * 3.14 for i in range(0, n): pygame.draw.line(Surface, color, position, (cos(i / n * pi2)...

Zipping ticklines does not allow to change their properties

python,matplotlib,python-3.4

I guess, there are twice as many ax.yaxis.get_ticklines() than there are ax.yaxis.get_ticklabels(), so zip just stops before painting them all, while individual loops are fine. This behaviour of zip is explained in the Python documentation....

Create modules for Linux install of PocketSphinx?

python,python-3.4,pocketsphinx

You can install the python modules for pocketsphinx and sphinxbase through pip. Just run: sudo pip install pocketsphinx The sphinxbase module is a requirement of pocketsphinx so it will be installed automatically when you install the pocketsphinx package. Then in your python program, you should be able to import modules...

Tkinter, Windows: How to view window in windows task bar which has no title bar?

python,windows,tkinter,python-3.4

Tk does not provide a way to have a toplevel window that has overrideredirect set to appear on the taskbar. To do this the window needs to have the WS_EX_APPWINDOW extended style applied and this type of Tk window has WS_EX_TOOLWINDOW set instead. We can use the python ctypes extension...

Fatal Python error when trying to run an executable Python script

python,python-3.4,cx-freeze

From the docs: Single-file executables cx_Freeze does not support building a single file exe, where all of the libraries for your application are embedded in one executable file. For a single-file solution using py2exe and others, see this question. In 3.5 there is also the new zipapp module, although the...

Why does round(5/2) return 2?

python,python-3.x,python-3.4

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). Quoting the documentation for the round function. Hope this helps :) On a side note, I would suggest always read the doc when...

Unexpected syntax error while using 'blit' on pygame [closed]

python,python-3.x,pygame,python-3.4

You are missing a closing parenthesis on the preceding line: img = pygame.transform.scale(img, (20,20) # ^ ^ ^? ...

Using os.path.join with os.path.getsize, returning FileNotFoundError

python,python-3.4

When you're reading in a file, you need to be aware of how the data is being seperated. In this case, the read-in file has a filename once per line seperated out by that \n operator. Need to strip it then before you use it. for file_name in file_lines: file_name...

multiprocessing.Pool.imap_unordered with fixed queue size or buffer?

python,sqlite,generator,python-3.4,python-multiprocessing

Since processing is fast, but writing is slow, it sounds like your problem is I/O-bound. Therefore there might not be much to be gained from using multiprocessing. However, it is possible to peel off chunks of data, process the chunk, and wait until that data has been written before peeling...

Uninstall Python package using pip3

python,pip,python-3.4,spyder

Go to /usr/local/bin and find the packages you want to delete Then just use sudo rm -r spyder or whatever the directory name is. That way the files get manually removed from your system....

Django ImportError: No module named 'app'

python-3.4,django-1.8

The path of managed.py looks unusual to me. managed.py is usually at the top level project directory. The problem you encounter stems from the fact that django roots the search path (i.e. sys.path) at the path of the managed.py script. In your case, common's relative module path is actually myapp.common....

Keeping Score in python code

computer-science,python-3.4

create a counter and add to it for correct answers. You can also create a counter for wrong answer Of course you want to declare these variables first. so the code to increment your counter would be like : rightAnswer += 1 if answer == riddle["correct"]: print("Congratz! You can think!!!")...

Using Boost.Python to build a shared lib and import it in Blender through Python

python,c++,blender,python-3.4,boost-python

After a lot of trial and error I got it working! I'll try to give a step by step tutorial on how to do that for OSX. In the next couple of weeks I'll also try to get it working on windows and will update this answer as I succeed!...

Is it possible to use pyvenv-3.4 without Python 3.4 installed?

python,virtualenv,python-3.4,python-2.x

I don't know if it's possible to do it that way but you can build any version of python in your home drive that you can use for development. What you do need is the the development tools installed for your distribution ie GCC etc. Step 1 download the source...

Python3 project remove __pycache__ folders and .pyc files

python,python-3.x,python-3.4,delete-file

I found the answer myself when I mistyped pyclean as pycclean: No command 'pycclean' found, did you mean: Command 'py3clean' from package 'python3-minimal' (main) Command 'pyclean' from package 'python-minimal' (main) pycclean: command not found Running py3clean . cleaned it up very nicely....

Loop through downloading files using selenium in Python

python,selenium,selenium-webdriver,web-scraping,python-3.4

You need to pass the filename into the XPath expression: filename = driver.find_element_by_xpath('//a[contains(text(), "{filename}")]'.format(filename=f)) Though, an easier location technique here would be "by partial link text": for f in fname: filename = driver.find_element_by_partial_link_text(f) filename.click() ...

BeautifulSoup invalid syntax in Python 3.4 (after 2to3.py)

python,python-3.x,beautifulsoup,python-3.4

BeautifulSoup 4 does not need manual converting to run on Python 3. You are trying to run code only compatible with Python 2 instead; it appears you failed to correctly convert the codebase. From the BeautifulSoup 4 homepage: Beautiful Soup 4 works on both Python 2 (2.6+) and Python 3....

Difference in package importing between Python 2.7 and 3.4

python,python-2.7,import,package,python-3.4

Python 3 uses absolute imports (see PEP 328 as @user2357112 points out). The short of it is that Python 3 searches from the root of each sys.path entry, rather than first consulting the module's directory as if it were a prepended entry in sys.path. To get the behavior you want...

Messy Python install? (OS X)

python,osx,python-2.7,mechanize,python-3.4

OS X comes with Python pre-installed. Exactly which version(s) depends on your OS X version (e.g., 10.10 comes with 2.6 and 2.7, 10.8 comes with 2.5-2.7 plus a partial installation of 2.3, and 10.3 comes with 2.3). These are installed in /System/Library/Frameworks/Python.framework/Versions/2.*, and their site-packages are inside /Library/Python/2.*. (The reason...

Python read and search String in a file

regex,python-3.4

Change re.search function like below. match = re.search(r'^(?! *#).*MaxClients ([^,]+)', line ) (?! *#) negative lookahead which asserts that the start of the line is not followed by a # symbol....