Gribouillis 1,391 Programming Explorer Team Colleague

For pip, you need C:\Python33\Scripts in the PYTHONPATH

Gribouillis 1,391 Programming Explorer Team Colleague

PATH and PYTHONPATH are 2 different things. You must update the PATH to contain C:\Python33, but be careful not to remove useful folders.

Edit: this tutorial may help you.

Gribouillis 1,391 Programming Explorer Team Colleague

You must set the PATH environment variable. It must contain a python directory (C:\Python34). Also, if you dont need 2 versions of python 3, you could uninstall python 3.3.

Gribouillis 1,391 Programming Explorer Team Colleague

I see that you have several installs of python on your computer. First type

python -c "import sys; print(sys.executable)"

in a cmd prompt, to see which is the default python. Assuming it is python 3.4, make sure the environment variable PATH contains the folders C:\Python34 and C:\Python34\Scripts (and not the other pythons). Then the pip command should be available. You should also check that the PYTHONPATH variable exists and contains your python library folders(perhaps C:\Python34\Lib).

See this page on python in windows.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps the pip executable is not on your path. Find the location of pip.exe in your file system. (If you can't find it, install Locate32 to find it)

Gribouillis 1,391 Programming Explorer Team Colleague

Did you run the pip installer first ?

Gribouillis 1,391 Programming Explorer Team Colleague

To use pip, in Windows, execute the program cmd, and type

pip install PyUserInput

in cmd's terminal window.

In ubuntu linux, open a terminal and type

sudo pip install PyUserInput

give your login password on request.

entropicII commented: I opened command prompt and typed in "pip install PyUserInput" and it returns: "'pip' is not recongnized as an internal or external command, operable program or batch file." Whats going on I downloaded it before and it doesn't seem to be working? +0
Gribouillis 1,391 Programming Explorer Team Colleague

The first thing you can do is raise an exception when this error is detected, for example:

class CannotGrabTime(Exception):
    pass

def findNST(html):
    NST = re.findall(r'<td id="nst">(.*) am', html)
    if NST == []:
        NST = re.findall(r'<td id="nst">(.*) pm', html)
    if not NST:
        raise CannotGrabTime
    p = re.compile('\d+')
    Times = p.findall(NST[0])
    return NST, Times

The next thing to do is to catch the exception at an appropriate level and correct the bot's behavior at that level. It could be in funtion checkRS() or in funtion main(), for example in checkRS

def checkRS(...):
    ...
    try:
        NSTC, TimeC = findNST(html)
    except CannotGrabTime:
        # corrective code here
        ...

or in main()

def main(...):
    ...
    try:
        firststock, html1 = checkRS()
    except CannotGrabTime:
        # corrective code here
        ...

It all depends on the code in these functions

Gribouillis 1,391 Programming Explorer Team Colleague

Don't forget the case where there is no line[0]:

lambda line: bool(line and (line[0] in string.digits))
Gribouillis 1,391 Programming Explorer Team Colleague

thanks, but it only needs to shift the supplied list_in, no need for an infinite sequence

I don't completely agree with you. See the following example which shows a list shifted by 3

>>> L = list("abcefg")
>>> L
['a', 'b', 'c', 'e', 'f', 'g']
>>> list(enumerate(L))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'e'), (4, 'f'), (5, 'g')]
>>> S = L[-3:] + L[:-3]
>>> S
['e', 'f', 'g', 'a', 'b', 'c']
>>> list(enumerate(S))
[(0, 'e'), (1, 'f'), (2, 'g'), (3, 'a'), (4, 'b'), (5, 'c')]

In the shifted list, the new index of each item is not increased by 3 as would be the case for a true shift. The new index of an item is

new_index = (old_index + 3) % 6

So it is actually a shift modulo n (the length of the list). The real question is: what do you want your program to do if the offset is negative or larger than the length of the list.

Gribouillis 1,391 Programming Explorer Team Colleague

I started with slackware about 20 years ago, then Red Hat, then Mandriva, until it died, but today, my favorite distro is Kubuntu because it works flawlessly. Kubuntu 14.04 LTS is supported untill 2019, and I'm expecting 5 peaceful years as a linux user with KDE, no ads, no bugs, no trouble :)

Gribouillis 1,391 Programming Explorer Team Colleague

Upload to where ? There is no general solution. It depends on the receiving site or computer.

apaulogy commented: uploading to sites linked to my app. +0
Gribouillis 1,391 Programming Explorer Team Colleague

On my .tdb files, the 'file' command gives

TDB database version 6, little-endian hash size 999 bytes

The correct command seems to be tdbtool

Gribouillis 1,391 Programming Explorer Team Colleague

I think you misunderstand the meaning of the raw strings. The important point is the sequence of characters that the string contains. You can see it by converting to a list. For example

>>> line = "\python\001tag\file.txt"
>>> list(line)
['\\', 'p', 'y', 't', 'h', 'o', 'n', '\x01', 't', 'a', 'g', '\x0c', 'i', 'l', 'e', '.', 't', 'x', 't']
>>> line = r"\python\001tag\file.txt"
>>> list(line)
['\\', 'p', 'y', 't', 'h', 'o', 'n', '\\', '0', '0', '1', 't', 'a', 'g', '\\', 'f', 'i', 'l', 'e', '.', 't', 'x', 't']
>>> line = "\\python\\001tag\\file.txt"
>>> list(line)
['\\', 'p', 'y', 't', 'h', 'o', 'n', '\\', '0', '0', '1', 't', 'a', 'g', '\\', 'f', 'i', 'l', 'e', '.', 't', 'x', 't']

In the first case, due to the interpretation of literal \ in code, python interpretes the sequence \001 as a single character with octal number 001, or hexadecimal \x01. In the same way \f is interpreted as the formfeed character \x0c. In the second case (raw string), the literal backslash is not special, and it is always interpreted as a backslash character. In the third case, we escape every backslash, and we obtain the same results.

For literal file names in windows OS, one would choose the second or third way.

In regular expressions, my advice is to always use raw strings, because one tries to produce strings for the regular expression language, where the backslash plays a special role. This role must not intermix with the special role that it plays …

Gribouillis 1,391 Programming Explorer Team Colleague

Another way, returning a list of integers

>>> import re
>>> def getints(string):
...     return [int(x) for x in re.findall(r'\d+', string)]
... 
>>> getints("foo23bar01-14qux2")
[23, 1, 14, 2]
Gribouillis 1,391 Programming Explorer Team Colleague

Did you try to query and change the screen resolution with the xrandr command ? See this blog entry for example. If a command line with xrandr works, you could perhaps add a script at startup to execute this command line.

Gribouillis 1,391 Programming Explorer Team Colleague

oh ok since i never copy anyone content, guess i'm fine?

It's not really the question. As a helper, I think it is useful to know that you are already getting help from someone else, not least because I can check if you already have a satisfactory answer. You already started many threads about different aspects of your program, and I think other helpers might want to check all the answers that you got.

Gribouillis 1,391 Programming Explorer Team Colleague

Using readlines() is a bad idea as it reads the whole file in memory. You could try something like the following code, which loads one line at a time

#!/usr/local/bin/python2.7
from __future__ import print_function

search_phrase = "Jul"
with open('input.txt','r') as f:
    data = enumerate(f, 1)
    try:
        while True:
            line_num, line = next(data)
            if search_phrase in line:
                print(line_num, line[2:26])
                nums = set([line_num + 2, line_num + 5, line_num + 8])
                while nums:
                    line_num, line = next(data)
                    if line_num in nums:
                        print(line_num, line)
                        nums.discard(line_num)
    except StopIteration:
        pass
Gribouillis 1,391 Programming Explorer Team Colleague

Yes, only you need to parse the two dates and may be write a loop to catch user errors, for example

from humanfriendly import parse_date, InvalidDate
from datetime import datetime

def ask_date(msg):
    while True:
        try:
            s = raw_input(msg)
            return datetime(*parse_date(s))
        except (InvalidDate, ValueError) as err:
            print(err)

dt1 = ask_date("From datetime: ")
dt2 = ask_date("To datetime: ")

You must also use dt1 and dt2 somewhere later in the code.

Edit: changed the except clause to catch ValueError.

Gribouillis 1,391 Programming Explorer Team Colleague

Install humanfriendly from pypi (pip install humanfriendly), then

from datetime import datetime
from humanfriendly import parse_date

s = raw_input('From datetime: ')
dt = datetime(*parse_date(s))
print(dt)
Gribouillis 1,391 Programming Explorer Team Colleague

I tried with the 22 data rows above. I had to replace line 36 with plt.show() and comment line 11. It seems to work and I don't know what you mean by the program will hang. I'm on linux x86_64 with python 2.7.

Gribouillis 1,391 Programming Explorer Team Colleague

Replace line 20 by the whole block of code.

Gribouillis 1,391 Programming Explorer Team Colleague
Help on method_descriptor in str:

str.zfill = zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.

I think it does exactly what you need. Another way is

>>> "{:0>4s}".format('123')
'0123'
Gribouillis 1,391 Programming Explorer Team Colleague

The story goes on: there is now PyUserInput which embeds pymouse and adds keyboard control too :). Install it from pypi.

Gribouillis 1,391 Programming Explorer Team Colleague

Are you really running windows 95 ? I thought it died more than 15 years ago. You could perhaps rewrite the editor for python 1.5 (which was a very good version of python).

Gribouillis 1,391 Programming Explorer Team Colleague

An alternative to what I wrote above is to create a per user site-packages directory (pep 370). In my kubuntu system it means typing

$ mkdir --parents ~/.local/lib/python2.7/site-packages

in a terminal. This directory is then automatically added to the python path when I run python. I can add my own scripts to the directory. For example if I have a file ~/Documents/daniweb/bargr.py, I can add a symbolic link

$ ln -s $HOME/Documents/daniweb/bargr.py $HOME/.local/lib/python2.7/site-packages/bargr.py

then I can use import bargr in python code from anywhere under my user name.

Another thing I can do with this directory is install modules from pypi in it, for example

$ pip install --user tabula

installs the pypi package tabula in my per-user site packages directory.

(I don't know what it does and there is no documentation, so

$ pip uninstall tabula

works too :)

Gribouillis 1,391 Programming Explorer Team Colleague

In the spirit of more than one way to do it ...

Notice that python came after perl, and in python,

There should be one-- and preferably only one --obvious way to do it.

type

import this

in the python console to read the Zen of python.

The description of the problem is almost a regular expression, so I would do it with the re module.

Gribouillis 1,391 Programming Explorer Team Colleague

Try

import eyeD3

To answer your second question, create for example a directory with

$ mkdir ~/pymods

in a terminal, then add the following lines to the file ~/.bashrc, and restart the terminal

PYTHONPATH="$HOME/pymods:$PYTHONPATH"
export PYTHONPATH

Now every python file added to the directory ~/pymods becomes importable
from anywhere (under your user name). For example create a file
~/pymods/abracadabra.py and use import abracadabra from anywhere.
You can also store python packages in pymods (directories containing a file __init__.py)
You can also add symbolic links to python files and packages.

There are other techniques for this, but it should be a starting point.

Gribouillis 1,391 Programming Explorer Team Colleague

One part of the question is why would we need an OS written in python ?

My advice is: go linux !

Gribouillis 1,391 Programming Explorer Team Colleague

Yes, only

  • There is no variable name in method FileName()
  • Usually, import statements are written at the beginning of the file.
  • Avoid import * as much as possible.
  • Module level code is often written in a block such as

.

if __name__ == '__main__':
    X =  returnDataFrame()
    X.FileName('F:/Python/Week05052013.csv') 
    WeeklyFile = DataFrame()
    WeeklyFile = WeeklyFile.append(X.returnFile())
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a short explanation about variable visibility

varA = "foo" # a global variable

class Bar: # Bar is another global variable
    varB = "baz" # a class variable

    def method(self, arg): # self and arg are local variables
        varC = "qux" # a local variable
        self.name = "aname" # an instance variable
        print( varA ) # no problem. global variables are visible
        print( Bar.varB ) # varB is an attribute of class Bar
        print( self.varB ) # varB can be accessed from instances as well
        print( varC ) # No problem
        print( varB ) # NameError. varB is not visible (nor global nor local)

Conclusion: import pandas in global namespace, not in class namespace.

Gribouillis 1,391 Programming Explorer Team Colleague

But only problem is the encoding, I mean to say, the Hindi characters are not to be seen in hindi, instead Unicode Characters.

It's because when you print the Counter object, python prints the repr() of the dictionary keys. The first thing to do absolutely is to use UNICODE. I mean that instead of

text = """..."""

use

text = u"""..."""

if you don't do that with literal Hindi text, you'll get
wrong results. An alternative is to write

from __future__ import unicode_literals

at the top of you python file. This makes literal strings be unicode in python 2 (which is the behaviour of python 3).

Then instead of printing the Counter object directly, you can use a loop

for key, value in c.items():
    print key, ':', value
Gribouillis 1,391 Programming Explorer Team Colleague

It would help if you could zip the jhi.txt file and attach it to a post. I think you must use u'\u0907\u0938' and not '\u0907\u0938'. Notice the leading u which means that we are creating a unicode string instead of a byte string. These are two completely different objects. Alternatively, use u'इस', with a leading u.

That's a point where python 2 and python 3 differ.

Gribouillis 1,391 Programming Explorer Team Colleague

I think you are probably using python 2.7 where literal strings are rows of bytes and not unicode. For example, here is my console output with python 2.7 in kubuntu:

>>> 'इस'
'\xe0\xa4\x87\xe0\xa4\xb8'
>>> 'इस'.decode('utf-8')
u'\u0907\u0938'
>>> s = 'इस'.decode('utf-8')
>>> s
u'\u0907\u0938'
>>> print(s)
इस
>>> 
>>> u'इस'
u'\u0907\u0938'

Conclusion: use u'इस' or 'इस'.decode('utf-8') in your console. The best rule is always work with unicode strings. This confines the encoding issues to

  • Reading and writing from/to files.
  • Reading and writing from/to console
  • Your source code encoding: declare the encoding at the top of your source code and make sure your editor produces this encoding.
Gribouillis 1,391 Programming Explorer Team Colleague

Don't forget the beautiful ninja IDE.

Gribouillis 1,391 Programming Explorer Team Colleague

The main concern is about encoding. If you know the file's encoding, you can open it with codecs.open() and read the file as a unicode stream. I never used a hindi file, so that you must figure out the encoding yourself. Once you have the correct unicode stream, the rest should be easy.

Gribouillis 1,391 Programming Explorer Team Colleague

I think logging.info() should be logger.info().

analys commented: still no output +0
Gribouillis 1,391 Programming Explorer Team Colleague

It is not true that fileis a reserved word in python. file is the name of a standard type in python 2. Using file as a variable name in python 2 is like using list as a variable name. It is not an error, but it could be annoying to the programmer because it hides the built-in name. For python >= 2.7, the list of reserved words is available as

import keyword
print(keyword.kwlist)
Gribouillis 1,391 Programming Explorer Team Colleague

First note that due to operator precedence the expression

A or B in C

is the same thing as

A or (B in C)

In particular if A is a non empty bytes such as b'artist=', the value of the whole
expression is A, which evaluates as True in a boolean context.

I think the best solution uses regular expressions:

>>> import re
>>> data = b'uie uiepe epno Artist=Mad Season ue lje blah'
>>> expr = re.compile(br'(?i)artist\=') # (?i) is for *case insensitive*
>>> match = expr.search(data)
>>> if match:
...     i = match.end()
...     print(data[i:i+10])
... 
b'Mad Season'
>>> 
Gribouillis 1,391 Programming Explorer Team Colleague

If you want the names only (and not the values of the variables), you can use the dir() function. Names with double underscores on both sides are normally reserved for python's internal mechanics. Here you have the global names

  • __builtins__: the default module __builtin__ (without s) which contains the builtin functions.
  • __name__: the python name of the current module, which is the string '__main__' for the main script, but it would be 'xml.dom.minidom' if this code was in the module xml.dom.minidom.
  • __package__: the name of the package containing the current module if any. It would be 'xml.dom' for module xml.dom.minidom.
  • __doc__: the documentation string of the current module if any.
  • sys: module sys if you wrote import sys somewhere.

In imported modules, there is usually also __file__, the system path to the file where the module's code was loaded if any.

Gribouillis 1,391 Programming Explorer Team Colleague

Add

print(repr(word))
print(list)

immediately before line 19 and post the output here.

Also 'list' and 'dict' are so common words in python that nobody uses them for variables.

Gribouillis 1,391 Programming Explorer Team Colleague

You're getting the error because char is of type bytes, and char[counter] is an integer. Also you initiliazed newchar as a str. At line 15, you can't add a str and an int. You could write

newchar = b'' # initialize as bytes
counter = 0

while counter < 30 and char[counter]:
    newchar = newchar + char[counter:counter +1] # bytes + bytes
    counter = counter + 1

However there is a much simpler way to remove trailing zero bytes:

newchar = char.rstrip(b'\x00')

Last, but not least, I tried with pygame/examples/data/house_lo.mp3 and the 125 last bytes are all space characters followed by exactly 1 null character.

Gribouillis 1,391 Programming Explorer Team Colleague

This snippet defines a function printat() which adds line and file information to the normal print() function output. The intended use is a quick and dirty debugging information for everyday's use. A more complete solution is to use a logging/debugging/tracing framework.

Gribouillis 1,391 Programming Explorer Team Colleague

You can perhaps add the condition that there is no uppercase letter before the first 3 ones or after the 3 last ones.

Gribouillis 1,391 Programming Explorer Team Colleague

The simplest way is

import easygui
word = easygui.passwordbox()

You can then browse the easygui source code to learn how to make a passwordbox :) and remove the buttons if you want to.

Spencer_3 commented: Could you send me a message? I have another question I got it to work now. +0
Gribouillis 1,391 Programming Explorer Team Colleague

This snippet implements a pointed set, that is to say an ordinary set of elements with a distinguished element called the basepoint of the set. For example the seven days of the week could be stored in a pointed set, the basepoint being monday because today is monday. It is a very simple structure but use cases are easily found.

Gribouillis 1,391 Programming Explorer Team Colleague

You can perhaps use tokenize.generate_tokens() which can parse a line or any piece of codes and give you token position (column).

Tcll commented: forgot to up-vote ;D +2
Gribouillis 1,391 Programming Explorer Team Colleague

I see 2 tools which could give you more detail:

  1. You can use sys.settrace() to define your own trace function and count the number of calls in each line (there is some programming effort to get something here).
  2. You can use f.f_lasti on the calling frame to get the precise bytecode instruction where the call was done. The bytecode could help you compute the position in source code.

Also, read the important Note here, and delete explicitely frames assigned to a variable.

Gribouillis 1,391 Programming Explorer Team Colleague

Add str(cnt).

By the way, this is better:

with open("foo.csv") as f: cnt = sum(1 for line in f)

because the file is properly closed.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a perhaps more readable version

try: from Tkinter import *
except ImportError: from tkinter import *
import time

root = Tk()
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)

def tick():
    s = time.strftime('%H:%M:%S')
    if s != clock["text"]:
        clock["text"] = s
    clock.after(200, tick)

tick()
root.mainloop()