Python Forum
Error in a file and problem with ptpython
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error in a file and problem with ptpython
#1
Hi all! First trouble: python works with version 3.7 while ptpython works with verion 3.6. How make them both work with 3.7 ?
Second trouble: I have a file made by a professionnal, still I have an error.
#!/usr/bin/env python

# Script Name		: prime_finder.py
# Author			: Tony Hammack
# Created			: 23 December 2015
# Last Modified		: 4 February 2016
# Version			: 1.5

# Classes imported
import logging
import os
import sys

from timer import Timer


# Classes created
class InvalidArgumentException(Exception):      # Custom Exception
    pass


# **** Constants ****
LOG_FILE = 'prime_finder.log'      # Log file
MINUTES = 0.5                 # user can define global duration in minutes that algorithm can use


# ***** Functions ***

# Utilities

def clear_screen():
    "# Function to clear the screen"
    if os.name == "posix":  # Unix/Linux/MacOS/BSD/etc
           return os.system('clear')  # Clear the Screen
    elif os.name in ("nt", "dos", "ce"):  # DOS/Windows
        return os.system('CLS')


def new_program():
    # New Program
    clear_screen()
    load_program()


def reload_finder():
    # reloads the program
    response = input("Do you want to restart the prime finder? (yes or no): ")
    if response == "yes":
        new_program()
    elif response == "no":
        clear_screen()
        sys.exit()  # closes form


def load_program( t= Timer):
    # Main Program

    # First Logger
    log_specifics_debug('START', 'Starting the Prime Finder.')

    # initial variable input
    try:
        # User input
        userString = input("Please input an integer: ")
        userNumber = int(userString)
        log_specifics_debug('USER INPUT', 'Input was successful.')

        # Initiates Timer class object
        t = Timer()
        start_time = t.start()

        # Prime Finder
        prime_finder(userNumber, start_time)
        log_specifics_debug('PRIME FINDER', 'prime_finder module completed.')

        # Reload prime finder
        response = input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            clear_screen()
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            sys.exit()

    except ValueError as err:
        log_specifics_debug('USER INPUT', userString)
        log_specifics_critical('USER INPUT', 'User entered a non-integer literal.')
        # Restarts Prime Finder application
        response = input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            clear_screen()
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            sys.exit()

    except KeyboardInterrupt as err:
        log_specifics_debug('Closing', 'User has manually closed program.')
        sys.exit()

    except RuntimeError as err:
        log_specifics_debug('RUNTIME ERROR', err)
        # Restarts Prime Finder application
        response = input("Do you want to restart the prime finder? (yes or no): ")
        if response == "yes":
            log_specifics_debug('RELOADING', 'Prime Finder is reloading.')
            new_program()
        elif response == "no":
            log_specifics_debug('CLOSING', 'Prime Finder is closing.')
            clear_screen()
            sys.exit()


# Prime Finder Algorithm
def prime_finder(num, p_start):  # prime factor algorithm
    log_specifics_debug('START TIME', 'Start of algorithm: ' + str(p_start))
    print("Here are your prime factors....")
    mod = 2
    while mod <= num:
        test = compare_time(p_start)
        if test:
            while num % mod == 0:
                num = num / mod
                final_output(mod)  # displays output
            mod += 1  # increases modulus by one
        else:
            print("Time of algorithm exceeded predetermined limit of: " + str(MINUTES) + " minutes.")
            break
    log_endoftime(p_start)


def final_output(factors):  # prints modulus out
    log_specifics_debug('FACTORS', factors)
    print(factors)

# Timer class objects


def start_time():           # Start Time
    t = Timer()
    return t.start()


def stop_time():            # Stop Time
    t = Timer()
    return t.stop()


def difference_time(p_start):           # Difference between start and end times
        stop = stop_time()
        return stop - p_start


def compare_time(p_start):      # Compares Time
    seconds = MINUTES * 60        # User can specify seconds to limit program
    while difference_time(p_start) < seconds:
        return True
    return False

# Loggers


def log_endoftime(p_start):
    log_stop = stop_time()
    log_specifics_debug('END TIME', 'End of algorithm: ' + str(log_stop))
    log_specifics_debug('LENGTH  TIME', 'Time of algorithm: ' + str(log_stop - p_start) + " seconds.")


def log_specifics_debug(section, message):          # Logs debug information with section/message
    log = logging.getLogger(section)
    log.debug(message)


def log_specifics_critical(section, message):       # Logs critical information with section/message
    log = logging.getLogger(section)
    log.critical(message)


def log_specifics_info(section, message):       # Logs critical information with section/message
    log = logging.getLogger(section)
    log.info(message)


def purge_log():
    with open(LOG_FILE, 'w') as file:
            file.truncate()


# *****Ends Functions****

if __name__ == "__main__":
    # set up logging to file
    logging.basicConfig(level=logging.DEBUG,
                      format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                      datefmt='%d-%m-%y %H:%M',              # Date Format
                      filename=LOG_FILE,                  # Name of log
                      filemode='a')                       # Appends log
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    # tell the handler  to use this format
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)

    # Starting program#
    try:
        if len(sys.argv) > 1:           # Checks to see if sys.argv has input
            argv = str(sys.argv[1])
            # purges logs
            if argv == '-p':
                purge_log()
                new_program()
            elif argv == '--purge':
                purge_log()
                new_program()
            else:
                # Raising Custom exemption
                raise InvalidArgumentException("User entered " + argv + " as invalid argument.")
        else:
            new_program()

    except InvalidArgumentException as err:
        log_specifics_debug('INVALID ARGV', err)
        sys.exit()

# **** End Program
Now the error:
Error:
Please input an integer: 145 Traceback (most recent call last): File "big.py", line 225, in <module> new_program() File "big.py", line 42, in new_program load_program() File "big.py", line 69, in load_program t = Timer() TypeError: Timer takes at least 2 arguments
Reply
#2
Second trouble: this code uses a module timer which we don't know where it comes from. However, I suspect it is this module from the cheeseshop, which runs this C code. As you can see in function Timer_new(), it takes at least 2 arguments: a time in microseconds and a python callback.

It is also possible that from timer import Timer invokes a different module on the author's computer and this timer module on yours, which would explain the error.
Reply
#3
I tried this:
  # Initiates Timer class object
        #t = Timer()
        t = Timer#added
        start_time = t.start()
and the new error is:
Error:
Please input an integer: 145 Traceback (most recent call last): File "big.py", line 226, in <module> new_program() File "big.py", line 42, in new_program load_program() File "big.py", line 71, in load_program start_time = t.start() TypeError: descriptor 'start' of '_timer.Timer' object needs an argument sylvain@sylvain-HP-Laptop-15-bw0xx:~$
Reply
#4
(Aug-24-2018, 05:10 PM)sylas Wrote: Hi all! First trouble: python works with version 3.7 while ptpython works with verion 3.6. How make them both work with 3.7 ?
You have to install ptpython to 3.7.
I guess you have gotten pyenv to work now.
Then both python and pip should point to 3.7.
# Set python and pip to point to 3.7
mint@mint ~ $ pyenv global 3.7.0
mint@mint ~ $ python -V
Python 3.7.0
mint@mint ~ $ pip -V
pip 10.0.1 from /home/mint/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pip (python 3.7)
mint@mint ~ $ 
Then pip install ptpython will install to 3.7,test with which pyinstaller Terminal.
Gribouillis Wrote:I suspect it is this module from the cheeseshop
No is this one prime_finder 0.1
New users may wonder cheeseshop Think

You should link to the code you use @sylas
Reply
#5
(Aug-25-2018, 09:13 AM)snippsat Wrote: New users may wonder cheeseshop
Cheeseshop reminds me of python more than 20 years ago. I think it's good to introduce new users to these prehistoric times. Python has a history, there is a blog by GvR about it.
Reply
#6
@snippsat: thanks, now python and ptpython use version 3.7.0
@all it is strange we cannot make work this professionnal file
Reply
#7
(Aug-25-2018, 09:36 AM)sylas Wrote: it is strange we cannot make work this professionnal file
Obviously, you're importing the wrong timer module. Use the timer module given in @snippsat's link.
Reply
#8
I uploaded the pack "PrimeFinder" of the same author(Hammack). So we can forget my previous file.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to handle "History" in ptpython sylas 4 4,027 Oct-07-2018, 11:09 PM
Last Post: Larz60+
  Cannot use functions at the bottom of ptpython sylas 1 2,224 Aug-29-2018, 12:02 PM
Last Post: sylas
  How to correct, save, run with ptpython sylas 17 9,081 Jun-03-2018, 04:48 PM
Last Post: sylas
  ptpython docstring metulburr 4 4,509 Nov-17-2017, 01:36 AM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020