FAQ Database Discussion Community


Pass function call as a function argument

python,python-2.7,python-3.x
Code: def function1(a,b): return a-1,b-1 def function2(c,d): return c+1,d+1 print function1(function2(1,2)) Error: Traceback (most recent call last): File "C:\Users\sony\Desktop\Python\scripts\twitter_get_data.py", line 6, in <module> print function1(function2(1,2)) TypeError: function1() takes exactly 2 arguments (1 given) [Finished in 0.1s with exit code 1] Why the above error? ...

“Initializing” variables in python?

python,python-3.x
Even though initializing variables in python is not necessary, my professor still wants us to do it for practice. I wrote my program and it worked fine, but after I tried to initialize some of the variables I got an error message when I tried to run it. Here is...

How do I output the acronym on one line

python,python-3.x
I am following the hands-on python tutorials from Loyola university and for one exercise I am supposed to get a phrase from the user, capatalize the first letter of each word and print the acronym on one line. I have figured out how to print the acronym but I can't...

index() Method Not Accepting None as Start/Stop

python,python-3.x
While writing a binary search method for a list I decided to use the builtin index() method on a smaller slice of the list determined via the binary search method. However in certain cases I was getting the error: TypeError: slice indices must be integers or None or have an...

Python - Why is my list turning into a tuple when passing it to a method with varargs (keywordonly)

python,python-3.x,varargs
I pass a list to a method which accepts multiple params (*values). If I pass multiple values separated by "," its all fine, but if I pass a list *values turns into a tuple and doesnt iterate the values and the only element is the list I would like to...

Understanding Super() in python

python,python-3.x,tkinter
class SeaofBTCapp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) Hello all I am trying to understand objects and classes. Using tkinter the author has created a class which inherits from the Tk() class of tkinter and proceeds to write his own __init__ method which I assume overrides...

“Initializing” a constant containing a file in python?

python,python-3.x
I know that initializing variables/constants in python is not necessary, but my professor still wants us to initialize variables for practice. In my program, I have a file to which I assigned a name: infile = open("studentinfo.txt", "r") How would it make sense to initialize the constant "infile"? Can I...

Regex: match “group3.*group1” if group2 is not between groups 3 and 1

regex,python-3.x,regex-negation,regex-lookarounds
I'm using Python 3.4. I have three groups: g1 = 'g11|g12' g2 = 'g21|g22' g3 = 'g31|g32' I want to match any instance of g3, followed by anything except g2, followed by g1. Here are some strings on which I want to find a match: 'g31 anything or nothing g11'...

Pyqt - Add a QMenuBar to a QMainWindow which is in another class

python-3.x,pyqt,pyqt5
I have 2 classes : MainWindow() and Menubar(). MainWindow() is a QMainWindow and Menubar is a QMenuBar. I don't know how I can add the menu bar to the main window. With the QToolBar, I can make something like this : self.toolbar = Toolbar() self.addToolBar(self.toolbar) But with the QMenubar, there...

How to make the Sieve of Eratosthenes faster?

python-3.x,primes,sieve-of-eratosthenes,number-theory
I am trying to solve the 10 problem in the Project Euler. It consists on finding the sum of all the primes below two million. I wrote the following code based on the Sieve of Eratosthenes. import time t0 = time.time() n=200000 liste=list(range(2,n)) k=2 s=2 while k <=n: liste=list(set(liste)-set(range(k,n,k))) if...

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?...

How do I make each histogram bin show me the frequency of each action/event/item?

python-3.x,matplotlib,histogram
I want to plot a histrogram showing the frequencies of various actions at different intervals. I want to bin the occurence of actions into 10 minute intervals. binwidth = 10*60 #10 minutes times = array([ 1.43431325e+09, 1.43431325e+09, 1.43431329e+09, 1.43431330e+09, 1.43431333e+09, 1.43431334e+09, 1.43431345e+09, 1.43431346e+09, 1.43431346e+09, 1.43431346e+09, 1.43431349e+09, 1.43431350e+09, 1.43431350e+09, 1.43431351e+09, 1.43431354e+09,...

Label keeps on appearing

python-3.x,tkinter
SO I am using Python 3.4 and tkinter. And when I call a function again n again which contains a label, the label keeps on appearing in window but previous label doesn't go away? How can I remove any printed label from GUI window as soon as function is called...

XML to custom Class

python,python-3.x
So, I'm retrieving data from one vShield Manager via the API and building a database to syncronize with another... I'm successfully retreiving XML from the API (yay) and I can parse it just fine, but it's a bit tedious. I'm trying to create custom classes for the various objects in...

RTC to Git Migration using rtc2git - https://github.com/WtfJoke/rtc2git

git,python-2.7,python-3.x,rtc
I need to migrate the source code from RTC SCM to Git along with the history. I have seen a post put in this link and tried downloading it from GitHub and I get compilation error when I execute the "migration.py" script. First I tried to Insatll Python version 3...

Installing Python 3 Docker Ubuntu error command 'x86_64-linux-gnu-gcc

python,python-3.x,amazon-web-services,docker
I'm trying to create a dockerfile that uses Python 3. FROM ubuntu:14.04 RUN apt-get update RUN apt-get install -y python3 python3-dev python-pip RUN apt-get install -y libxml2-dev libxslt1-dev libpq-dev libjpeg-dev libfreetype6-dev zlib1g-dev RUN cd /var/projects/apps && pip install -r requirements.txt I get the error fatal error: Python.h: No such file...

Python 3.4 : LXML : Parsing Tables

python,python-3.x,datatables,lxml
I want to parse an entire table from yahoo finance. As I understand it 'tbody' and 'thead' tags are not registered by lxml but rather as additional TR so I switched the xpath from: /html/body/div[4]/div[4]/table[2]/tbody/tr[2]/td/table[2]/tbody/tr/td/table/tbody to what is seen in the code below url = 'http://finance.yahoo.com/q/is?s=MMM+Income+Statement&annual' tree = html.parse(url) tick_content...

Pylint Error when using metaclass

python,python-3.x,vim,pylint,syntastic
i try to fix all pylint errors and pylint warnings in a project. but i keep getting an error when i set a metaclass (https://www.python.org/dev/peps/pep-3115/). here is my example code: #!/usr/bin/env python3 class MyMeta(type): pass class MyObject(object, metaclass=MyMeta): # pylint error here pass the error just says "invalid syntax". i...

How to avoid user to click outside popup Dialog window using Qt and Python?

qt,user-interface,python-3.x,dialog,qt-creator
I created a Dialog window using Qt Creator and Python. I would like that Window stays on the top of my Gui AND avoid users to click outside that Dialog Until this dialog was closed.

Django runserver not serving some static files

django,python-3.x
My local testing server for Django v1.8.2 on Windows 8.1 is only serving certain static files. Others are giving a 404 error. #urls.py - excerpt urlpatterns = [ url(r'^$', views.index) ] + staticfiles_urlpatterns() #settings.py - excerpt INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', 'users' ) STATIC_URL =...

python 3 error with print function syntax

python,python-3.x,printing
I have a list of lists with tuples. I want to get the length of a tuple using: item1=(4, 8, 16, 30) list6=[[(4, 8, 16, 29)], [(4, 8, 16, 30)], [(4, 8, 16, 32)]] print("list6.index((4, 8, 16, 29)):",list6.index([item1])) print("len(list6[1]):"), len(list6[1]) Output: list6.index((4, 8, 16, 29)): 1 len(list6[1]): There is no...

Error Hashing + Salt password

python,authentication,python-3.x,hash,salt
Someone can help me to fix this problem: TypeError: can't concat bytes to str I am trying to safely store hash+salt passwords, I think the problem is that my salt is a byte object how can I transform it into a string? Or is there a way to hash it...

Music21 Midi Error: type object '_io.StringIO' has no attribute 'StringIO'. How to fix it?

python,python-3.x,music21
So, I've followed this question in order to get some sound playing with Music21, and here's the code: from music21 import * import random def main(): # Set up a detuned piano # (where each key has a random # but consistent detuning from 30 cents flat to sharp) #...

Python3:socket:TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'

sockets,python-3.x
I am try to use python socket package to implement an echo server. But it continuously occurs the error: TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes', is there any errors in my code? here is the error: Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/threading.py",...

Python bruteforce combinations given a starting string

python,python-3.x,brute-force
I'm trying to do a bruteforce string generator in Python and itertools.combinations_with_replacement seemed to do just the trick. gen = itertools.combinations_with_replacement('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',12) for combination in gen: check(''.join(combination)) Say the user runs the program for some hours and reaches up to string aaaeabdouzIU. Is there any way given a string where they...

Setting unique=True on a ForeignKey has the same effect as using a OneToOneField

python,django,python-3.x,django-models,django-1.8
I switched to Django 1.8.2 from 1.7 recently, but I encounter with a little bit issues, for example in one of my models I have: class Author(models.Model): author = models.ForeignKey(UserProfile, blank=False, primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) But when I run server I come across with this following warning: WARNINGS: exam.Author.author: (fields.W342)...

Python custom sort

python,sorting,python-3.x
I am trying to sort a list using Python's sorted function. In Python 3 the cmp keyword argument was removed. Unfortunately it seems that I can not implement my algorithm using the key keyword argument since I both objects in order to compare the data. Example Sorted Data 59 59...

argparse optional value for argument

python,python-3.x,command-line-interface,argparse
I want to distinguish between these three cases: The flag is not present at all python example.py; The flag is present but without a value python example.py -t; and The flag is present and has a value python example.py -t ~/some/path. How can I do this with Python argparse? The...

The event loop is already running

python,python-3.x,pyqt,pyqt4
I have the following 5 files: gui.py # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)...

subprocess python 3 check_output not same as shell command?

python-3.x,subprocess
I am trying to use the subprocess module in python but its a bit tricky to get working. Here's my code import sys import os import subprocess import shlex def install_module(dir_path, command): c = shlex.split(command) os.chdir(dir_path) try: p = subprocess.check_output(c, shell=True) except subprocess.CalledProcessError as e: #print('install failed for: ' +...

Python 3 random.randint() only returning 1's and 2's

function,python-3.x,random,dice
I thought I'd finally worked out all the kinks in the dice rolling code I wrote for practice, but then apparently I forgot to save my work last night, and when I rewrote it this afternoon, the random.randint function didn't seem to be returning any numbers other than 1's and...

Python - Function that sums list's with error

python,list,function,python-3.x
def somalist (lista): listasoma = [0,0,0,0,0,0,0,0,0,0,0] for i in lista: for g in i: if i.index(g) != 0 and i.index(g) != 1 and i.index(g) != 2 and i.index(g) != 3: listasoma[i.index(g)] += g else: listasoma[i.index(g)] = g print(listasoma) return(listasoma) x = [[1,2,3,4,5,6,7,8,9,10,11],[1,2,3,4,5,6,7,8,9,10,11],[1,2,3,4,5,6,7,8,9,10,11]] print(somalist(x)) is that the function, it works doing...

Python3 string and hmac auth

string,file,python-3.x
I made a pice of code that works, where they key and secret are declared in the code such: key = 'ewjewej2j020e2' secret = 'dw8d8d8ddh8h8hfehf0fh' Then do my business and works. But if i put key and secret in an external file in two lines separated by a newline carrier...

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...

Why is rounding done like this? [on hold]

python,python-3.x,rounding
Why is Python rounding like this? >>> 1.12345678901234567890 1.1234567890123457 >>> 0.0001100110011001100110011001100110011001100110011 0.00011001100110011001 ...

Python file processing?

python,python-3.x
My assignment was to write a program which extracts the first/last names, birth year, and ID from a file, manipulate that information to create a username and formatted ID, prompt the user for 3 test grades, calculate the average, and finally write all the information to a new file. This...

Need Help in Python Variable updation (Pygame module)

python,python-2.7,variables,python-3.x,pygame
I am trying to increase my speed variable in my pygame code. But as i run this piece of code the speed remain 0.1 (if i press UP key) and 0 (else case). I am unable to debug this. Any help in this would be greatly appreciated. import pygame speed...

Put a QLineEdit() into a QTreeWidgetItem()

python,python-3.x,pyqt,pyqt5
Is it possible to put a QLineEdit() into a QTreeWidgetItem() in order to modify the text of the QTreeWidgetItem ? Here is my code def addItemsToTree(self, parent, text, checkable=False, expanded=True): self.item = QTreeWidgetItem(parent, [text]) if checkable: self.item.setCheckState(0, Qt.Unchecked) else: self.item.setFlags(self.item.flags() & ~Qt.ItemIsUserCheckable) self.item.setExpanded(expanded) min = QLineEdit() max = QLineEdit() self.addChildTree(self.item,...

django-admin startproject not working with python3 on OS X

python,django,osx,python-2.7,python-3.x
I have python3 installed with Django 1.8.2 on Mac OS. There is also python 2.7 installed by default with the OS. When trying to run startproject I get - $ django-admin startproject mysite Traceback (most recent call last): File "/usr/local/bin/django-admin", line 7, in <module> from django.core.management import execute_from_command_line ImportError: No...

scipy.integrate.quad gives wrong result on large ranges

python,python-3.x,scipy,integration,quad
I am trying to integrate over the sum of two 'half' normal distributions. scipy.integrate.quad works fine when I try to integrate over a small range but returns 0 when I do it for large ranges. Here's the code: mu1 = 0 mu2 = 0 std1 = 1 std2 = 1...

Nested maps in Python 3

python,python-3.x,lambda
I want to transform my list list = [" a , 1 ", " b , 2 "] into a nested list [["a","1"],["b","2"]]. The following works: f1_a = map(lambda x :[t.strip() for t in x.split(',',1)],list) but this does not work with Python 3 (it does work with Python 2.7!): f1_b...

Trouble outputing file size to a label from a listbox in Python 3

python-3.x,operating-system
I'm using os.path.getsize() to output the size of a file to a label. The file path is stored in a listbox. The function works, but it outputs the file size in bits, so I wrote the following to convert to more appropriate units, and it is now displaying only in...

TCL parsing a list of arguments to an external call

python,python-3.x,tcl
Im trying to execute a call to a python script through aldec riviera-pro my call is python $python_app_name $python_app_args However my $python_app_args are passed as a single string and not multiple strings resulting in that the python application only sees it as one argument and its execution fails. I've tried...

Cancel last line iteration on a file

python,python-3.x,for-loop,file-io
I need to iterate on a file, stop iteration on a condition and then continue parse the file at the same line with another function (That may change so I can't just add content in the previous function). An example file (file.txt) : 1 2 3 4 5 6 7...

Python 3.4: List to Dictionary

python,list,python-3.x,dictionary
I have a string as follows : ['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-',...

Quotes within quotes

python,string,python-3.x,double-quotes
In Python 3.x: print(""s"") # SyntaxError print("""s""") # prints s print(""""s"""") # SyntaxError print("""""s""""") # prints ""s What is the reason behind this different behaviour, when there are different numbers of double quotes in the string?...

multiple iteration of the same list

python,python-2.7,python-3.x,numpy,shapely
I have one list of data as follows: from shapely.geometry import box data = [box(1,2,3,4), box(4,5,6,7), box(1,2,3,4)] sublists = [A,B,C] The list 'data' has following sub-lists: A = box(1,2,3,4) B = box(4,5,6,7) C = box(1,2,3,4) I have to check if sub-lists intersect. If intersect they should put in one tuple;...

Python MVC style GUI Temperature Converter

python,user-interface,python-3.x,model-view-controller,tkinter
#The view (GuiTest.py) import tkinter import Controller class MyFrame(tkinter.Frame): def __init__(self, controller): tkinter.Frame.__init__(self) self.pack() self.controller = controller #Output Label self.outputLabel = tkinter.Label(self) self.outputLabel["text"] = ("") self.outputLabel.pack({"side":"right"}) #Entry Space self.entrySpace = tkinter.Entry(self) self.entrySpace["text"] = ("") self.entrySpace.pack({"side":"left"}) #two convert buttons self.convertButton=tkinter.Button(self) self.convertButton["text"]= "Fahrenheit to...

Finding the number of letters in a sentence?

python,python-3.x
I am trying to write a program to find the total number of letters in a sentence. I would like to know why my program is wrong. This is what I tried: words = ["hi", "how", "are", "you"] alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",...

Multiple random choices with different outcomes

python,python-3.x,random
I'm trying to make a random NPC generator in Python--the last time I tried this, it was in PHP, and that went. . . strangely. What I'd like to be able to do with this is to call the defined variables within the string multiple times. I can do that...

Vim - how to run current python3 file in the python shell?

python,python-3.x,vim
I have a file called myFile.py on my desktop. This is the file: class Node: def __init__(self, data, next): self.data = data self.next = next def __str__(self): self = node while node.next: print(node.data) node = node.next return node.data I normally edit the file in IDLE. In IDLE I can click...

xmlrpclib error 'module not found' when trying to access gandi api

python,api,python-3.x,xml-rpc
I am trying to set the DS record in the gandi api as describded in the gandi api support doc It states to 'import xmlrpclib' but I immediately get an error 'module not found' (full text reproduced below). I found this page where they use 'from xmlrpc import client', but...

Receiving “NO CARRIER” error while tring to make a call using GSM modem in Python

python,python-3.x,gsm,at-command,modem
I want to make a call using my GSM modem. So I wrote the below program: import time import serial recipient = "+98xxxxxxxxxx" phone = serial.Serial("COM10", 115200, timeout=5) try: time.sleep(0.5) phone.write(b'ATZ\r') time.sleep(1) phone.write(b'ATD"'+recipient.encode() +b'"\r') while(1): print(phone.readline()) time.sleep(0.5) finally: phone.close() But when I run it I receive this output: >>> ================================...

If a block of code creates an error, do x; if not, do y (Python)

python,python-3.x
In Python, is it possible to test for an error in a block of code, and if one shows up, do something; if not, do something else? The psuedo-code would look like checkError: print("foobar" + 123) succeed: print("The block of code works!") fail: print("The block of code does not work!")...

Execute multiple command lines with multiple arguments

python,windows,batch-file,python-3.x
I can't figure out why my command lines doesn't function. I tried subprocess.Popen()` function : `Popen('C:/Test/test.exe -scan "C:/Users/Vince/test.txt" "C:/Users/Vince/test.xml"', cwd='C:/Users/Vince/Working_Directory') But when I run a batch file from my Python program by using os.system("E:/test.bat"), it functions. Here is the content of my batch file: C: cd Users\Vince\Working_Directory C:\Test\test.exe -scan "C:\Users\Vince\test.txt"...

How to have multiple text widgets with scrollbars in a frame on tkinter

python,python-3.x,tkinter
I want my text widgets to have scrollbar capability within each text widget. I have created a canvas and within it have embedded a frame using create_window. I then put 2 Text widgets into this frame. I want each of the text widgets to have a scrollbar, however when I...

Set comprehensions in Python and testing for membership in the set being created

python,python-3.x,set-comprehension
This is actually question about the semantics of set comprehensions, but I first need to explain the context. I'm trying to create a new set of tuples where the paired value in the touple is unique regardless of the order of the values in the pair. Simplifying my actual program,...

Getting Error on Running brand New project from Pycharm on Mac

django,python-3.x
I am Very new to Django 1.8 I have install Python 2.7 ,2.6 and 3.5 I tried creating project with all version. I created project in PyCharm using Django everything is ok. Now I Run the project and I got huge error /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/nileshjarad/Python/Django/First/manage.py runserver 8000 Traceback (most recent call...

writing a tkinter scrollbar for canvas within a class

python,python-3.x,tkinter
I've searched around and cannot seem to find an answer for my problem. I am trying to create a working scrollbar for the following code and cannot seem to get it to work. The problem appears to be with the OnFrameConfigure method. I have seen elsewhere that the method should...

tkinter showerror creating blank tk window

python-3.x,tkinter,messagebox,tkmessagebox
I have a program that needs to display graphical error messages to users. It is a tkinter GUI, so I am using tkinter.messagebox.showerror When I call showerror, it shows the error, but also creates a blank "tk" window, the kind created when an instance of the Tk class is called,...

Scroll through a tkinter frame or window [duplicate]

python-3.x,scroll,tkinter,scrollbar
This question already has an answer here: Adding a scrollbar to a grid of widgets in Tkinter 1 answer I am creating a window that will be quite long, and I want to have a scrollbar to be able to scroll vertically through the window (it's a settings window)....

Python3 - sorting a list

python,list,python-3.x
I don't understand why 1 and 5 are printed three times. (I know I could use the list.sort() method.) lst = [4,5,5,1,6,1] copy = lst.copy() sort = [] for i in range(len(lst)): min_ = min(copy) for k in copy: if k == min_: sort.append(min_) copy.remove(min_) print(sort) ...

What is a reliable isnumeric() function for python 3?

python,regex,validation,python-3.x,isnumeric
I am attempting to do what should be very simple and check to see if a value in an Entry field is a valid and real number. The str.isnumeric() method does not account for "-" negative numbers, or "." decimal numbers. I tried writing a function for this: def IsNumeric(self,...

How to parse this string?

python,python-3.x
I have a string like the below string: >>> string = """00 1f 00@ 00c 00e 00N 00> 00E 00O 00F 002 00& 00* 00/ 00) 00 1f 00 1c 00 00 00 17 00\r 00 08 00 03 00 f8 ff ea ff e1 ff e1 ff e0 ff...

Wrapping Functions in Python 3.4 missing required positional argument

python,python-3.x,flask,flask-login
I am trying to customize a login_required decorator from the Flask-Login package. I have read the source code and mimicked the syntax. Mine: def login_role_required(f, req_roles=['any']): @wraps(f) def decorated_view(*args, **kwargs): if current_app.login_manager._login_disabled: return f(*args, **kwargs) if not current_user.is_authenticated(): return current_app.login_manager.unauthorized() if req_roles == ['any']: return f(*args, **kwargs) user_roles = current_user.get_roles...

Split long column into several columns and print them side by side

python,python-3.x,multiple-columns
Using this code: import string for i, j in enumerate(string.ascii_uppercase, 1): print('{}: {}'.format(i, j)) I get the following output: 1: A 2: B 3: C 4: D 5: E 6: F 7: G 8: H 9: I 10: J 11: K 12: L 13: M 14: N 15: O ......

sys.argv in a windows environment

python,windows,python-3.x
I'm attempting to learn python using the book 'a byte of python'. The code: import sys print('the command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') outputs: the command line arguments are: C:/Users/user/PycharmProjects/helloWorld/module_using_sys.py The PYTHONPATH is ['C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Python34\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']...

Python3 input() error: can't initialize sys standard streams

ubuntu,python-3.x
I'm running Python 3.4.3 on Ubuntu 15.04 and just encountered a very strange problem when trying to use the input() function. To isolate the problem Iv'e created a file called test.py contaning: print(input()) When running it, I receive this error: $ python3 test.py Fatal Python error: Py_Initialize: can't initialize sys...

Python 3.3 TypeError: can't use a string pattern on a bytes-like object in re.findall()

python-3.x,web-crawler
I am trying to learn how to automatically fetch urls from a page. In the following code I am trying to get the title of the webpage: import urllib.request import re url = "http://www.google.com" regex = '<title>(,+?)</title>' pattern = re.compile(regex) with urllib.request.urlopen(url) as response: html = response.read() title = re.findall(pattern,...

Python 3.x AttributeError: 'NoneType' object has no attribute 'groupdict'

regex,python-3.x
Being a beginner in python I might be missing out on some kind of basics. But I was going through one of the codes from a project and happened to face this : AttributeError: 'NoneType' object has no attribute 'groupdict' Following is the section of code,re-phrased though,still this does result...

How to access a class's property using a partialmethod?

python,python-3.x,descriptor
I have a need to create many similar functions in class definitions using their properties. To me, it makes perfect sense to use partial functions for this. However, the properties are not passing what I want to the partial methods (e.g. the property object is being passed, not what it...

re.split return None in function but normaly works OK

python,python-3.x,split
def whois(k, i): k = str(k[i]) print (k) whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE) ou, err = whois.communicate() who = str(ou) print (who.find('NetName:')) who = re.split('NetName:', who)[1] who = re.split('NetHandle', who)[0] who = who.replace(r'\n', '') print (whois(k, 4)) Output: 108.160.172.204 520 None Why python return "None" not "Dropbox"? If i...

TypeError: object is not JSON serializable in DJango 1.8 Python 3.4

python,json,django,python-3.x,serialization
I'm using DJango 1.8 and Python 3.4 When the below view is being ran, Django throws Type Error - Object is not JSON Serializable Views.py from django.http import HttpRequest,HttpResponse from django.http import JsonResponse from json import dumps def get_stats(request): if request.method == "POST": srch_dropV = request.POST['srch_dropAJ'] else: srch_dropV = ''...

Works in shell but not as a program?

python,python-3.x
I tried the following in the shell infile = open("studentinfo.txt", "r") infile.read() And it returned the text in the file, which is what I want it to do. However, when I wrote it and saved it as a program def main(): infile = open("studentinfo.txt", "r") infile.read() main() It just returned...

Python 3 filtering directories by name that matches specific pattern

python,regex,python-3.x,directory,filtering
Currently I'm developing script that will perform cleanup of specific directories. For example: Directory: /app/test/log contains many sub-directories with name pattern testYYYYMMDD and logYYYYMMDD What I need, is to filter out only directories like testYYYYMMDD To get all folders with absolute path that are in given directory I use: folders_in_given_folder...

Why does '12345'.count('') return 6 and not 5?

python,python-3.x,count
>>> '12345'.count('') 6 Why does this happen? If there are only 5 characters in that string, why is the count function returning one more? Also, is there a more effective way of counting characters in a string?...

Return to main fuction in python

python-3.x,def
Working on Python 3.4.3 Let's say I have created three fuctions: def choosing(mylist=[]): print("We will have to make a list of choices") appending(mylist) done = False while(done == "False"): confirm = input("Is your list complete?[Y/N]") if(confirm == "Y"): print("Yaay! Choices creation complete." "{} choices have been added successfully".format(len(mylist))) done =...

Callable not defined for django.db.models field default

python,django,python-3.x,django-models
I am using PyCharm 4.5.2, Django 1.8.2. If I define a class as: class User(models.Model): first_name = models.CharField(max_length=256) last_name = models.CharField(max_length=256) slug = models.SlugField(max_length=256, unique=True, default=make_slug) def make_slug(self): return self.first_name + self.last_name[0] The IDE highlights default=make_slug with make_slug being undefined. The interpretter agrees and when the development server tries to...

How to create an item list to use multiple times on a Jinja2 template page?

python,python-3.x,for-loop,flask,jinja2
I want to create an HTML option list and display it multiple times on the template page. I tried to iterate through the list passed on to the template but this seems only to work once on the page: {% for item in points %} <option value="{{ item }}">{{ item...

How to detect certain numbers from a dice roller?

python,python-3.x,dice
I have made a text-based RPG that uses dice rolling for the combat system. If you get a 1, your attack is forfeited. You can keep rolling until you get a one, or type 'attack'. I made a dice roller, and I just want to know, how to make it...

Python3 after cursor.execute it stopped?

mysql,python-3.x
After much trying on python3 (as of still new in this language), the line whereby cursor.execute will prevent the for loop to continue when condition met. However when I comment cursor.execute line, the looping able to continue until the end. How can I made it continue till the last result...

Python Reuse a Variable in the Else Block of an If-Else Statement

python,python-3.x,if-statement,condition
I'm currently working on a simple file transfer program in Python. I am having trouble with the function for prompting the user for the location of the folder to be copied. def getSrc(): if getSrc.has_been_called is False: source = askdirectory() getSrc.has_been_called = True return source else: return source getSrc.has_been_called =...

How can I customize the offset in matplotlib

python-3.x,matplotlib
I would like to customize the offset use in matplotlib. Specifically: Set the limits when used (similar to power limits for scientific notation) Customize the format string on both the axis ticks. Doing so with ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%.1f')) switches the scientific notation off. Thank you for the answer, in case somebody encounters...

multiprocessing.Pool with maxtasksperchild produces equal PIDs

python,python-3.x,multiprocessing,pid
I need to run a function in a process, which is completely isolated from all other memory, several times. I would like to use multiprocessing for that (since I need to serialize a complex output coming from the functions). I set the start_method to 'spawn' and use a pool with...

Addition of two dates on python 3

python,csv,datetime,python-3.x
I try adding date and hours from csv file in one datetime variable. I read questions about adding some timedelta and official doc https://docs.python.org/3/library/datetime.html#timedelta-objects, but don't understend how it works. My csv row looks like - ['2005.02.28', '17:38', '1.32690', '1.32720', '1.32680', '1.32720', '5'].I convert row[0] = 2005.02.28 to date and...

Python3.x - counting occurences of all substrings using dictionaries

python-3.x,substring
Given some string S, this code will count the number of occurrences of all possible substrings of the string S. #count[i]=no of different substrings in the string that occurs exactly i times count=[0]*(100001) a=input() dic={} n=len(a) for i in range(n): temp="" for j in range(i,n,1): temp+=a[j] if temp in dic:...

Python3 create files from dictionary

file,python-3.x,dictionary
I have a dictionary in a function which is called searchInMyDict(dict) for example. The dictionary included in that function has for key a group name and has for value a list of gene's functions. the dictionary looks like : {"OG_1": ["gene's functionA, gene's functionB, gene's functionC"] "OG_2": ["gene's functionM, gene's...

csv.writerows() puts newline after each row

python,csv,python-3.x
This is an example from the O'Reilly Cookbook (truncated dataset) headers = ['Symbol','Price','Date','Time','Change','Volume'] rows = [{'Symbol': 'AA', 'Volume': 181800, 'Change': -0.18, 'Time': '9:36am', 'Date': '6/11/2007', 'Price': 39.48}, {'Symbol': 'AIG', 'Volume': 195500, 'Change': -0.15, 'Time': '9:36am', 'Date': '6/11/2007', 'Price': 71.38} ] with open('stocks2.csv','w') as f: f_csv = csv.DictWriter(f, headers) f_csv.writeheader() f_csv.writerows(rows)...

Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?

python,list,python-2.7,python-3.x,reduce
I've achived these two things. Find all possible sublists of a list in given range (i ,j). A = [ 44, 55, 66, 77, 88, 99, 11, 22, 33 ] Let, i = 2 and j = 4 Then, Possible sublists of the list "A" in the given range (2,4)...

Trivial functors

python,python-3.x,functor
I very often write code like: sorted(some_dict.items(), key=lambda x: x[1]) sorted(list_of_dicts, key=lambda x: x['age']) map(lambda x: x.name, rows) where I would like to write: sorted(some_dict.items(), key=idx_f(1)) sorted(list_of_dicts, key=idx_f('name')) map(attr_f('name'), rows) using: def attr_f(field): return lambda x: getattr(x, field) def idx_f(field): return lambda x: x[field] Are there functor-creators like idx_f and...

How to have parameters to a button command in tkinter python3 [duplicate]

python,function,python-3.x,tkinter
This question already has an answer here: Python Tkinter: Passing arguments to Button widget 1 answer commands in tkinter when to use lambda and callbacks 2 answers I want to have UI where when I press a button, stuff pops up in the console. The issue is the stuff...

XML file parsing - Get data from a child of a child

python,xml,parsing,python-3.x
I know how to get data from a child tag but I would like to get data from a child tag of a child tag of the "root" tag. We can use this database for example : <DB> <Entry> <Name></Name> <DisplayName>Assembly.iam</DisplayName> <Scalar> <Name>d0</Name> <DisplayName>d0 (value = 0 mm)</DisplayName> <Value>0</Value> </Scalar>...

python contextmanager newline issue

python,python-3.x,contextmanager
Using Python's contextmanager I want to generate a wrapper to display Linux-like progress of a certain block of code: Doing something... done. [42 ms] This is working - kind of: from contextlib import contextmanager import time @contextmanager def msg(m): print(m + "... ", end='') t_start = time.time() yield t_duration_ms =...

LXML - parse td content within tr tag

python,html,python-3.x,lxml
I want to parse each individual statistic from the yahoo finance tables for formatting purposes - when parsing the entire table the formatting is terrible!! I am currently using the code below and I would have to repeat the 4 lines of contentA code slightly altered to retrieve the stats...

Converting list to array with NumPy asarray method

python,csv,python-3.x,numpy
I try get mean from csv line. I get data from csv in string list, further i convert it to array with numpy. Its work perfect when i try plot some graphics. But when i calculate mean i get some errors with my data. If i use NumPy i get:...

My simple client crash everytime it tries to connect to my python socket server

python,sockets,python-3.x,serversocket
My client crash everytime it tries to connect to my python socket server. I dont know why but but my server seams to start up fine then when i start up my client it establishes a connection to the server but it crash direct. Im doing almost as what they...

Cleaner regex for removing characters before dot or slash

python,regex,python-3.x
Is there a cleaner regex than the following? I know I can search for two different regex at the same time by combining them with |. I'm removing everything before the first occurrence of a . or - by the following regex and the extra space after these. re.sub("^[^-]*- |^[^.]*....

What's the fastest way to compare datetime in pandas?

python,python-3.x,numpy,pandas,datetime64
I have two big csv files with different number of rows which I am importing as follows: tdata = pd.read_csv(tfilepath, sep=',', parse_dates=['date_1']) print(tdata.iloc[:, [0,3]]) TBA date_1 0 0 2010-01-04 1 9 2010-01-05 2 0 2010-01-06 3 8 2010-01-07 4 0 2010-01-08 5 0 2010-01-09 pdata = pd.read_csv(pfilepath, sep=',', parse_dates=['date_2']) print(pdata.iloc[:,...

The command “sudo apt-get install python-dev, python3-dev” failed and exited with 100 during

python,python-2.7,python-3.x,command-line,pip
It seems like sudo apt-get install build-essential worked just fine but, but it gets error while installing python-pip. Here's the log of the failed build....

weird behaviour of late import and scopes

python,python-3.x,cpython
I have just discovered this strange scoping behaviour of both Python 2 and 3. When I'm adding a late import for a sub-module, the main import of toplevel module stops working. Viable example: import os def start(): import sys print('in modules?', 'os' in sys.modules) print('in globals?', 'os' in globals()) print('in...