FAQ Database Discussion Community


If statement looking for float is not working

python,python-3.4
I'm learning Python, and I wrote a simple script that creates a list of tasks I need to do today. After putting an input on the task to be done, I have the script ask how long it will take to do that task. It would work in adding the...

Python 3.4 Pandas DataFrame Structuring

pandas,dataframes,python-3.4
QUESTION How can I get rid of the repeated column labels for each line of data? CODE req = urllib.request.Request(newIsUrl) resp = urllib.request.urlopen(req) respData = resp.read() dRespData = respData.decode('utf-8') df = pd.DataFrame(columns= ['Ticker', 'GW', 'RE', 'OE', 'NI', 'CE']) df = df.append({'Ticker':ticker, 'GW':gw, 'RE':rt, 'OE':oe, 'NI':netInc, 'CE':capExp}, ignore_index= True) print(df) yhooKeyStats()...

Create modules for Linux install of PocketSphinx?

python,python-3.4,pocketsphinx
I am trying to get Python 3.4 working with PocketSphinx on a Linux (Ubuntu 14.04 OS) machine. Yesterday, I successfully installed both sphinxbase-5prealpha and pocketsphinx-5prealpha. I confirmed my install by successfully running pocketsphinx_continuous -inmic yes I'm trying to move on to the Python API for but can't find the python...

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

linux,firefox,jenkins,python-3.4
I have installed jenkins as a service on linux mint. I am trying to run tests written in python and script cannot run firefox. This line is a problem. ... self.browser = webdriver.Firefox() ... When i log in as jenkins user, i can't run firefox. getting this error : (process:3758):...

how to append in a specific line in file in python 3?

python,file,python-3.4
I am making a program for my computer science assignment. I need to make a quiz for 3 classes in a primary school. Then the results have to be saved in a file. I've done the program till here but the next task asks me to let each student have...

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

python,command-prompt,python-3.4
if I installed Python program in my E drive not C drive, is it the necessary that I must execute python files in the same drive that I installed python program in Command Prompt? for example, I installed Python Program in my E drive. I can only be allowed to...

Keeping Score in python code

computer-science,python-3.4
What do I have to do in order to have a score board for my code because I need a score board. I tried a while statement but got lost there. Can you help me? So lost. import random def main_menu(): option = input("Play the game (P) , View the...

Python read and search String in a file

regex,python-3.4
I want to write a script to read apache.conf file and get "MaxClients" value, "Keepalive" value,"KeepAliveTimeout" value and "ServerLimit" value etc, to different arguments. But it should not be read if the line start with "#" value. I have written sample code as below, but it is not ignoring #...

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

python-3.4,urlparse
I'm not exactly sure what these modules are used for. I get that they split the respective url into its components, but why would that be useful, or what is an example of when to use urlparse?

Converting a List within a List from String to Integers

python,type-conversion,python-3.4
After approximately eight hours of searching and attempting to implement solutions, I am still vexed by this problem. I am attempting to make a dinky ANOVA package that can read data from a text file, count the number of participants based on lines within said file, and then run an...

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

python,python-3.4,py.test
Following the example at http://py.readthedocs.org/en/latest/path.html#basic-interactive-example import py temppath = py.test.ensuretemp('py.path_documentation') Raises the error AttributeError: 'module' object has no attribute 'ensuretemp' Python version 3.4.3, py version 1.4.26. In [1]: import py In [2]: dir(py.test) Out[2]: ['Class', 'Collector', 'File', 'Function', 'Generator', 'Instance', 'Item', 'Module', 'Session', 'UsageError', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',...

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

regex,python-3.4,python-2.x,backport
Python 3.4 introduced the new regex method re.fullmatch(pattern, string, flags=0). Has anyone back-ported this new method to older Python versions?...

Print into console terminal not into cell output of IPython Notebook

python,windows,ipython,ipython-notebook,python-3.4
I would like to print into the terminal window that runs IPython Notebook and not into the cell output. Printing into cell output consumes more memory and slows down my system when I issue a substantial number of print calls. In essence, I would like this behaviour by design. I...

Python: Why are decimals approximated?

python-3.4
I was experimenting with the IDLE Python 3.4.0 shell, and executed the following code. >>> from decimal import * >>> getcontext().prec = 500 >>> e = Decimal(2.4) >>> print(e) 2.399999999999999911182158029987476766109466552734375 As you can see, I set the variable e equal to exactly 2.4, nothing more, nothing less. However, when I...

python 3.4 modules can be install because numpy

numpy,python-3.4
I try to install some python module like vispy , pandas , pyqtgraph... and I got some errors : vc_env = query_vcvarsall(VERSION, plat_spec) File "C:\Python34\lib\site-packages\setuptools\msvc9_support.py", line 52, in query_vcvarsall return unpatched['query_vcvarsall'](version, *args, **kwargs) File "C:\Python34\lib\distutils\msvc9compiler.py", line 287, in query_vcva rsall raise ValueError(str(list(result.keys()))) ValueError: ['path'] I used this command : pip3.4...

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

python,git,python-3.4,atlassian-stash,gitpython
I am trying to write a script (probably python) that needs to fetch a remote repo (housed with Stash via git), and checkout a specific commit (based on the hash). The problem is that this needs to happen 'blindly' to the user, but it pauses for a password. I need...

Can't upload file and data in same request in Flask test

python,flask,python-3.4,flask-testing
Hi i'm trying to test and endpoint that will need a file and some values, when i upload only the file there is not problem, but when i add the values it throws: TypeError: 'str' does not support the buffer interface my code is like this: headers = {'content-Type': 'multipart/form-data'}...

How to override __str__ in nested class

python,pydev,python-3.4,nested-class
I've coded a parent class and a nested class. I've already overridden the parent class __str__ method and now I want to do the same on the nested class. But for some reason the __str__ method in the nested class is not getting called. And I can't see the instance...

Is there a PyMOD(DEINIT)_FUNC?

python,python-3.4,python-c-extension
I want to know whether there is a PyMOD(DEINIT)_FUNC?, I know that resources are released when the python script exits, but I would like to make my code as responsible for the memory it uses as possible. I have searched the documentaion of course, and until now I think there...

Inserting row into SQLite table

python,sqlite3,python-3.4
I'm trying to add a row (post submitted by user) into a SQLite table (posts). I need to add the new post with the timestamp being the current time and date and then i need to return the id for this new post. My code so far (incomplete as im...

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

python,python-3.4
Both of them are python from documents : the first one says: If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define__get__() are called non-data descriptors (they are typically used for methods but other uses are possible). the second one says: If...

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

python,input,tkinter,python-3.4
I have written a script simulating a card game in Python where the user decides how many cards and how many piles of cards they want to play with. This input is controlled by following code where boundary_1 and boundary_2 give upper and lower limit in an integer interval and...

Creating matrices in Numpy?

python,numpy,python-3.4
I've tried different ways but I can't understand why I cannot create a matrix in numpy. I get a "TypeError: new() takes from 2 to 4 positional arguments but 5 were given" error when I call: def createGST(dictionary): x = int(dictionary['x']) y = int(dictionary['y']) z = int(dictionary['z']) matrix = np.matrix(...

Weird behaviour with len and str.splitlines()

python,string,typeerror,python-3.4
I'm making a HTTP request with the requests library and I want to make a Simple Response Object that parses my data. The problem I'm having is the following. When passing the response object to my ApiResponse I split the Response.text in lines, to count them and know if it...

Can't make PyQt5 Gui work, python3

python-3.4,pyqt5
i've made several guis with Qt Designer and then with PyQt5 i converted the .ui to .py, however, whenever i run this code on python3 nothing happens, no gui, no errors, nothing, i'm quite new to python and i have no idea why this is happening. -- coding: utf-8 --...

Difference in package importing between Python 2.7 and 3.4

python,python-2.7,import,package,python-3.4
For this directory hierarchy: . ├── hello │   ├── __init__.py │   └── world │   └── __init__.py └── test.py And the Python source files: test.py: if __name__ == '__main__': import hello hello/__init__.py: import world hello/world/__init__.py: print("yes you win") Running test.py with Python 3.4 throws ImportError saying that module world is not...

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

plot,list-comprehension,python-3.4,nested-lists
I have a nested list such that; nested_list = [[4, 3, 0], [6, 8, 7], [3, 1, 8], [2, 1, 3], [9, 9, 3], ...] which has 100 entries. I need to plot a graph of all the first elements of each sub-list where Sub_List_1 = [4, 6, 3, 2,...

Can you set cwd for abspath?

python,path,python-3.4
I am trying to expand out a relative path into an absolute path. The relative path will sometimes in include a . which will need to be expanded out from the current working directory. I was wondering if the any standard functions in Python accept a cwd kwarg, like subprocess.popen...

Create an exe with Python 3.4 using cx_Freeze

python,python-3.4,cx-freeze
I have found two other articles about this problem on Stack Exchange but none of them has a clear answer: is it possible to create a .exe of a Python 3.4 script? The only solution I found was to use cx_Freeze. I used it, and it indeed created an executable...

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

python,windows,tkinter,python-3.4
I created a window: root = Tk() and removed the titlebar: root.overrideredirect(True) Now the window is not on the task bar in windows. How can i show it in the task bar? (I only want to bring my window to the front if other windows are on top of mine)...

Python 3 Combobox issue?

combobox,tkinter,python-3.4
I am stuck with middle of the development, Need some help to resolve this. I want to add the Combobox to my interface and selection should come from text file.Text file have all the list of items. I want to put text file list to combobox and after select and...

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

python,osx,pyqt4,python-3.4,cx-freeze
I have a gui that has a mac task bar menu, see below: The first 3 items on the menu were created using QtDesigner and their sub items and actions connect fine. I created the extra "file" dynamically to see if this would fix the problem. This menu appears exactly...

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

python,sqlite,generator,python-3.4,python-multiprocessing
I am reading data from large CSV files, processing it, and loading it into a SQLite database. Profiling suggests 80% of my time is spent on I/O and 20% is processing input to prepare it for DB insertion. I sped up the processing step with multiprocessing.Pool so that the I/O...

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

python,csv,replace,python-3.4
I'm using python 3.4.3 I am very new to python and stack overflow, I'm trying to calculate averages from csv columns, some boxes contain question marks and wont let me convert them to float (obv) does anyone know how I can tell python to skip over the question marks or...

NetworkX Graph object not subscriptable

python,python-3.x,python-3.4,networkx
I was trying to monkey patch the NetworkX Graph object without typing out networkx.Graph.method_name = method_name for every single method I defined. I tried this (minimal version): import networkx class _GraphExtended (networkx.Graph): def is_nonnull(self): return bool(self.nodes()) for key in _GraphExtended.__dict__: nx.Graph[key] = _GraphExtended[key] and I got the error "'type' object...

Python/Pygame: Placing text in a specific location

python,pygame,python-3.4
In my code, I am trying to place a text box in a specific location. screen = pygame.display.set_mode((1000, 600), 0, 32) #Set the window to 1000x600 WHITE = (255, 255, 255) BLUE = (0, 0, 255) text = font.render('Start', True, BLACK) textRect = text.get_rect() What does the last line do,...

python memory usage dict and variables large dataset

python,python-3.4
So, I'm making a game in Python 3.4. In the game I need to keep track of a map. It is a map of joined rooms, starting at (0,0) and continuing in every direction, generated in a filtered-random way(only correct matches for the next position are used for a random...

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

python-3.4
I have two python files, one is the gui, the other contains all of the functions, say i have a class named Backend like in the code below, and one of its functions is "print1(self)", and i want to use that "print1" function inside of the second file in the...

Bounce back animation difficulty with space invaders clone

python,pygame,python-3.4
import time import pygame import random player = pygame.image.load('player.png') BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 255, 0) class enemy(pygame.sprite.Sprite): def __init__(self, color): super().__init__() self.image = pygame.Surface([10, 15]) self.image.fill(color) self.rect = self.image.get_rect() enemy_spd =...

Pickle user inputs - Python 3 [closed]

python,pickle,python-3.4
I am pretty desperate, since I have tried to get this working in a long time. I'm making a text adventure where some user inputs choose the player's hp, dmg, you name it. I want to make a save function, but every time I load it, the player has default...

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

python,windows,registry,python-3.4,winreg
I inserted a registry key, HKEY_LOCAL_MACHINE\SOFTWARE\test\test_qword of type REG_QWORD and value 20150509091344 (0x1253a7efba10). I then tried to load it using winreg with the following code in Python 3.4: import winreg key_dir = r"SOFTWARE\test" reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_dir, 0, winreg.KEY_WOW64_64KEY+winreg.KEY_ALL_ACCESS) test_dir = list(winreg.QueryValueEx(reg, r'test_qword'))[0] print(test_dir) ans = "".join(map(lambda b: format(b, "02x"),...

DRF Browsable API only shows one Router

django,django-rest-framework,django-urls,python-3.4
Essentially, depending on the order in which I add my routes to my urlpatterns the browsable API will only show one router at a time. Here's my code: urls.py: from django.conf.urls import url, include from rest_framework import routers from .views import PlantViewSet # url router router = routers.DefaultRouter() router.register(r'plants', PlantViewSet,...

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

python,c++,blender,python-3.4,boost-python
What I currently try to achieve is building a python mapping of my C++ classes through Boost.Python. After this I want to use the resulting shared library in a blender add-on to be able to take advantage of already existing functionality coming from the mapped C++ classes. I can already...

VIM: Use python3 interpreter in python-mode

python,vim,ubuntu-14.04,python-3.4,python-mode
I have recently switched to vim and configured it for Python-programming using this tutorial. Before, I have made sure that vim supports python3 (vim --version shows +python/dyn and +python3/dyn) using this article. But when executing a file from python-mode, still the python2.7 interpreter is chosen. How can I configure vim...

Embedding Python in Linux program

python,c++,linux,python-3.4,python-c-api
I am currently trying to embed Python in my C++ application to give the user advanced scripting possibilities. My program is working great on Windows so far (it is fully working), and now I'm trying to do the same on GNU/Linux (Debian 7 for now) but this is giving me...

How to set the inline image opaque in QtConsole3?

python,python-3.4,qtconsole
I run QtConsole3 with thw following command: ipython3 qtconsole --cache-size=4000 --matplotlib=inline --colors=Linux And plot a figure with following lines: In [1]: import numpy as np In [2]: import matplotlib.pyplot as plt In [3]: x = np.linspace(-1, 1, 1024) * 4 * np.pi In [4]: y = np.sin(x) / x In...

does the order when defining functions in classes in python matter

python,function,class,python-3.4
When defining a function within a class in python 3.x does it matter in which order you define functions ? Is class code pre-complied before you would call the class in main ? ...

Drawing pentagon,hexagon in Pygame

python,algorithm,pygame,python-3.4
I'm trying to make functions that can draw pentagon hexagon etc. Troubling on algorithm, should I compare the lines with pygame.draw.line ? It looks like too much work around the determine coords of lines. Is there an easy way to draw them? Also I don't know another library that can...

Uninstall Python package using pip3

python,pip,python-3.4,spyder
I am working with Python 3.4 and have installed a package (spyder) using pip3 install. It is works as it should and I can start it from the terminal. Since I want to switch my IDE, I tried to uninstall it using pip3 uninstall in the same way as the...

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
Why is my client timing out at code line: response = yield from asyncio.wait_for(reader.read(), timeout=3.0) instead of getting a message back? The server piece only registers it got a message from this client after the client times out and I actually issue a ctrl + d to kill the Python...

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
Let me preface this by saying I'm not exactly sure what is happening with my code; I'm fairly new to programming. I've been working on creating an individual final project for my python CS class that checks my teacher's website on a daily basis and determines if he's changed any...

Response Time Accuracy

python,time,python-3.4,psychopy
I am going to program a response time experiment in Python 3.4 with Pygame and PIL. Will Python's builtin time functions be accurate enough for a millisecond level accuracy of response times? Is PyParallel necessary, or is it necessary only for EEG or eye-tracking experiments?

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

for-loop,random,python-3.4
I'm trying to create a list with random length filled with lists of random lengths by using this code: import random solitaire = [None]*(random.randint(1,5)) for pile in solitaire: number = random.randint(0, 10) solitaire.append(number) print(solitaire) Easy enough I thought but when I ran this code my powershell window froze as it...

Total Beginner: Python 3.4 spot the syntax error

python-3.4
When running the following code, I get an error as follows: for (x in List[0] and y in range(0,11)): ^ SyntaxError: invalid syntax I am very new to Python programming. When I try to run the iteration at the top I get the above error-message. Could someone please kindly explain...

Using python dict imported from file in another python file

python,dictionary,python-3.4
I've the same issue as asked by the OP in How to import or include data structures (e.g. a dict) into a Python file from a separate file. However for some reason i'm unable to get it working. My setup is as follows: file1.py: TMP_DATA_FILE = {'a':'val1', 'b':'val2'} file2.py: from...

How can i make a startmenu in python?

python,menu,python-3.4,2d-games,startmenu
i have been trying to add a start menu to a game i have been making and have looked everywhere to see how to make a start menu. I did try to use a tutorial by sentdex but it didn't work for my code! And i have also looked in...

Defining django models in an alphabetic order

django,python-3.x,python-3.4
Can I define django models in an alphabetic order? Models taken from django tutorial: from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I'd like for Choice to be defined before the Question. After simple...

Python3 run os.popen with argument?

subprocess,popen,python-3.4
I am facing difficulties to run below query. Can some one help me to what is the issue on it ? def test(): cmd="python /home/shanaka/volapp/volatility-2.3.1/vol.py -f /home/shanaka/memory_sample/ubuntu-12.04-amd64-jynxkit.mem ---profile={0} {1}".format(OSselection.get(),option.get()) f1 = os.popen3(cmd) for lt in f1.readlines(): print(lt) This is not printing, Option.get is taking as another command, an error as...

Python igraph for windows 64bit

python,igraph,python-3.4
I am looking for python-igraph package for windows 64bits. I have installed python 3.4 and it seems that I can not find proper igraph installation package for it. I have crawled all webpages and still could not find what I am looking for. Can anyone help me please? Thanks...

Proper use of lambda in function definition

python,string,lambda,python-3.4
I want to write a simple function that recognizes palindromes: >>> def palindrome(s): return s == s[::-1] It works fine but it is case sensitive and to fix that I could do: >>> def palindrome(s): return s.lower() == s[::-1].lower() >>> palindrome('Aba') True but I figure it's not very elegant. I...

How To Achieve Python3.4 Virtualenv For Precise64 VirtualBox

django,virtual-machine,ubuntu-12.04,ansible,python-3.4
I'm trying to create virtualbox using precise64, Vagrant, and Ansible. I am able to get python2.7 virtualenv setup, but would like to use python3.4 instead. I cloned the ansible-django-stack repository and everything works, but it is using version 2.7. What should I change in order to get a python3.4 Virtualenv...

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

python,python-3.4
In conjunction with my last question, I'm onto printing the filenames with their sizes next to them in a sort of list. Basically I am reading filenames from one file (which are added by the user), taking the filename and putting it in the path of the working directory to...

Messy Python install? (OS X)

python,osx,python-2.7,mechanize,python-3.4
I am a complete beginner to both Python and the OS X Terminal, and I have attempted to install some packages for both Python 2.7.3 and Python 3.4. I can't get mechanize to work with neither Python 2 or Python 3 after install. I get: >>> from mechanize import *...

Connect to FTP TLS 1.2 Server with ftplib

python,ssl,ftp,python-3.4
I try to connect to a FTP Server which only supports TLS 1.2 Using Python 3.4.1 My Code: import ftplib import ssl ftps = ftplib.FTP_TLS() ftps.ssl_version = ssl.PROTOCOL_TLSv1_2 print (ftps.connect('108.61.166.122',31000)) print(ftps.login('test','test123')) ftps.prot_p() print (ftps.retrlines('LIST')) Error on client side: ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:598) Error on server side:...

Loop through downloading files using selenium in Python

python,selenium,selenium-webdriver,web-scraping,python-3.4
This is a follow-up question to this previous question on how to download ~1000 files from Google Patents. I would like to iterate through a list of filenames fname = ["ipg150106.zip", "ipg150113.zip"] and simulate clicking and saving these files to my computer. The following example works for me and downloads...

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

python,python-3.x,python-3.4
I am trying to write an on-the-fly bz2-compressed csv file in python3. Without compression this works fine: from csv import DictWriter FIELDNAMES = ('a', 'b') OUT_CSV = 'out.csv' DATA = ({'a': 1, 'b': 2}, {'a':3, 'b':4}) # works fine with open(OUT_CSV, 'w') as file_pointer: csv_writer = DictWriter(file_pointer, fieldnames=FIELDNAMES) csv_writer.writeheader() for...

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

python,dictionary,nltk,python-3.4
I am trying to create my own digital Spanish to English database by translating the entire Spanish corpus found in nltk 3.0 for python 3. I am using the Google tool-kit to do the translating and its proving to be a very slow process. i am wondering if there exists...

Are there memory limitations when outputting to a ScrolledText widget?

memory,logging,textbox,tkinter,python-3.4
I am fairly new to Python and to GUI programming, and have been learning the Tkinter package to further my development. I have written a simple data logger that sends a command to a device via a serial or TCP connection, and then reads the response back, displaying it in...

Zipping ticklines does not allow to change their properties

python,matplotlib,python-3.4
I was trying to reduce my code footprint to make it more readable when I stumbled around an odd result. If I run the following code: y1 = np.linspace(1,1000) y2 = np.linspace(10,1) c = ["b","g"] fig, ax = plt.subplots() ax.plot(y1, c[0]) ax2 = ax.twinx() ax2.plot(y2, c[1]) for tl in ax.yaxis.get_ticklines():...

Lift and raise a Canvas over a Canvas in tkinter

python,python-3.x,canvas,tkinter,python-3.4
I'm creating a game, and I am using tkinter to build the GUI. In this game, I want the user to start with a window, filled by a Canvas, with an image as background, and some buttons in some sort of item windows. And this Canvas is the home Canvas...

Invoking an earlier version of python in cmd

windows,python-2.7,python-3.4
I've installed Python 2.7 and python 3.4 on my system. Earlier i was using 3.4 but now require 2.7 as well (for a course I'm taking, which requires some files which are not there for 3.4). When I type python in cmd it by default initializes 3.4. Is there some...

Python import doesn't work when file is imported

python,python-3.4,python-import,python-module
I am having difficulties to understand how the python importer works.. I have a python script (fractalDimension.py) that imports a submodule ("greedyColoring.py") using: from boxCovering.greedyColoring import * It works fine when I call it directly: python fractalDimension.py The problem began when I moved the script to a folder and added...

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

python,python-3.x,pygame,python-3.4
import pygame import sys from pygame.locals import * pygame.init() white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,255,0) blue = (0,0,255) yellow = (255,255,0) cyan = (0,255,255) purple = (255,0,255) bg = black fps = 30 dispWidth = 800 dispHeight = 600 pixMove = 10 UP =...

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

pip,python-3.4
What command should I use in command prompt to install requests module in python 3.4 version ??? pip install requests is not useful to install requests module in python 3.4 version. Because while running the script below error is coming ImportError : no module named 'requests'...

Comparing tuples to strings

python,sqlite,python-3.4,bottle
I am trying to retrieve a user from my sessions table in the database. In my unit test i get an error: line 138, in test_session_user self.assertEqual(nick_from_cookie, nick) AssertionError: ('Bobalooba',) != 'Bobalooba' I understand that this is because my code is returning a tuple when the test is comparing my...

Subclass `pathlib.Path` fails

oop,python-3.4
I would like to enhance the class pathlib.Path but the simple example above dose not work. from pathlib import Path class PPath(Path): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) test = PPath("dir", "test.txt") Here is the error message I have. Traceback (most recent call last): File "/Users/projetmbc/test.py", line 14, in <module>...

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

python,osx,parsing,urllib,python-3.4
I'm trying to build a simple Python script algorithm on Mac OS X that has four parts to it. go to a defined website and grab all the HTML using urllib parse the HTML data to find a table of numbers (using beautifulsoup) with those numbers do a simple calculation...

Django ImportError: No module named 'app'

python-3.4,django-1.8
I have been using django 1.3 by now. But wanted to start with latest version 1.8.1 with python3.4I have started with the project. Here is my directory structure: ├── myapp │   ├── common │   │   ├── admin.py │   │   ├── __init__.py │   │   ├── migrations │   │   │   └── __init__.py...

Python ast parsing exception

python-2.7,abstract-syntax-tree,python-3.4
I was using ast module of python3.4 to get the imports and function calls within a file. It works correctly if I run the code on a file which has python3.4 syntax but throws an exception if I try to parse a file of older python2.7 version (for print statements,...

Tkinter self.grid making widgets invisible

python,tkinter,python-3.4
I am making a username/password confirmation using tkinter, and I've run into a problem where the widgets are no longer showing. """ Password entry/confirmation class """ from tkinter import * class Menu: def __init__(self,master): frame = Frame(master) frame.pack() title_username = Label(master, text="User Name") title_username.grid(row=0, column=0) title_password = Label(master, text="Password") title_password.grid(row=1,...

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

python,sqlite,sqlite3,python-3.4
The aim of this code is to validate a password that is entered using the passwords and usernames stored in a database. The table contains username(nick) and password, passwords are encrypted using: My code at the moment consists of: def check_login(db, username, password): """returns True if password matches stored""" cursor...

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

python,python-3.4
I tried this , this, but didn't helped me much, getting same error still any idea whats causing the issue in below code. try: request = urllib.request.Request(url,data=payload,method='PUT',headers={'Content-Type': 'application/json'}) response = urllib.request.urlopen(request) except Exception as e: print(str(e)) Error got:- Content-Length should be specified for iterable data of type class 'dict' Python...

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

python,python-3.x,beautifulsoup,python-3.4
I am trying to install Beautiful Soup 4 in Python 3.4. I installed it from the command line, (got the invalid syntax error because I had not converted it), ran the 2to3.py conversion script to bs4 and now I get a new invalid syntax error. >>> from bs4 import BeautifulSoup...

Python3 project remove __pycache__ folders and .pyc files

python,python-3.x,python-3.4,delete-file
What is the BEST way to clear out all the __pycache__ folders and .pyc/.pyo files from a python3 project. I have seen multiple users suggest the pyclean script bundled with Debian, but this does not remove the folders. I want a simple way to clean up the project before pushing...

Fatal Python error when trying to run an executable Python script

python,python-3.4,cx-freeze
I have a Python script that I have turned into an executable using cx-freeze-4.3.4.win32-py3.4. I have Python 3.4 installed on a Windows 7 64-bit machine. Here is my simple setup.py file: from cx_Freeze import setup, Executable setup( name = "myfilename" , version = "0.1" , description = "This is my...

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

python,datetime,python-3.x,python-3.4
I can convert a given date string formatted in YYYY-MM-DD to a datetime object using: from datetime import datetime dt = datetime.strptime(date_str, '%Y-%m-%d') However, this uses the current machine's timezone by default. Is there a way to specify a specific timezone (such as UTC, PST, etc) in the conversion so...

How to run selenium tests in jenkins?

unit-testing,selenium,jenkins,automated-tests,python-3.4
I have selenium tests written in python 3.4. How to run them from jenkins after success build ? Process is : 1. pull from git repository 2. python setup.py build 3. python setup.py install After that i need to run server and selenium tests....

Limited traceback running python -m

python,debugging,python-3.4
I am having a problem getting an informative traceback when I run a script with the -m flag. I am using the -m flag so that I can properly use relative imports throughout my package. When an error comes up, stdout does tell me the nature of the exception but...

How to run qtconsole connected to ipython3 instance?

ipython,python-3.4,qtconsole
When I run %qtconsole from within ipython3 I get ERROR: Line magic function%qtconsolenot found., but ipython3 qtconsole in terminal starts fine. According to this, how can I run qtconsole instance connected to ipython3 instance? And how to run it on a single core -- rc[0].execute(%qtconsole)? P.S. If someone know, tell...

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

python,python-3.4,python-asyncio
I have an event loop that runs some co-routines as part of a command line tool. The user may interrupt the tool with the usual Ctrl + C, at which point I want to clean up properly after the interrupted event loop. Here's what I tried. import asyncio @asyncio.coroutine def...

Installing Ghost.py

python,installation,python-3.4,ghost.py
I have installed new system and time has come to install Python and modules I have lost.. I had no problems with BeautifulSoup but can't make Ghost.py into work! Using Fedora 21 and Python-3.4.3. I have tried pip install pyside and then pip install ghost but I guess it worked...

Why does round(5/2) return 2?

python,python-3.x,python-3.4
Using python 3.4.3, round(5/2) # 2 Shouldn't it return 3? I tried using python 2 and it gave me the correct result round(5.0/2) # 3 How can I achieve a correct rounding of floats?...

Python 3.4.3 Tkinter TTK file not opening

python,tkinter,python-3.4,ttk
When I double click the .pyw file it doesn't run the code and open the GUI. It worked in 2.7 but I don't know. from tkinter import * from tkinter import ttk import os root = Tk() root.geometry('%dx%d+0+0' % (180 ,200)) root.title('Title Headder') def run1(): #os.startfile("scripts\test.pyw") print("Hello") mainframe = ttk.Frame(root,...

SQLite database query (Python, Bottle)

python,sqlite,python-3.4,bottle
I'm trying to make a function where that returns the name of the logged in user if one can be identified or None if not. i want to do this by finding the session id from the cookie in the Bottle request if present, and using it to look up...

Creating Pascal's Triangle using Python Recursion

python,recursion,python-3.4
I'm working on a homework assignment that asks me to create a Pascal Triangle using a recursive function. Below is what I've managed so far along with what I was given to work with. I'm quite new to Python and programming so I've got no idea where to head from...

Trying to write function map() getting error IndexError: list index out of range

python,function,dictionary,python-3.4
I'm trying to write function map() getting error IndexError: list index out of range def map1(fn, a): i = 0 b = [] while i != len(a): print(len(a)) i += 1 b.append(fn(a[i])) return b with working function def translate(x): dicti = {"merry": "god", "christmas": "jul", "and": "och", "happy": "gott", "new":...

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

python,virtualenv,python-3.4,python-2.x
I need to use Python 3.4 on a CentOS system where only Python 2.x is available. But I don't have privileges to install new software. Is there a way to use pyvenv-3.4 without Python 3.4 installed? E.g. I would download and unpack Python 3.4: wget https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz tar -xvzf Python-3.4.1.tgz and...

how can I add text to these rectangles?

python,text,menu,pygame,python-3.4
This is the code I have started to use to make a start menu. # we need some colours!! black = (0,0,0) white = (255,255,200) red = (200,0,0) green = (0, 200, 0) bright_red = (255, 0 ,0) bright_green = (0, 255, 0) bright_white = (255, 255, 255) def main():...

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

mongodb,python-3.4
I have have a Python application that is iteratively going through every document in a MongoDB (3.0.2) collection (typically between 10K and 1M documents), and adding new fields (probably doubling/tripling the number of fields in the document). My initial thought was that I would use upsert the entire of the...

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

python,dll,clr,python-3.4,python.net
I created a python script that uses pythonnet. The script is in a file named main.py. When I run the script from the command line (simply typing main.py at the Windows command prompt), the imported pythonnet module clr works fine. But when I try to build an exe I get...