Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
General Make_Python_Easier script
#1
This is an importable file that i have been working on.
It has no specific purpose other than to add some features to python to make it easier.
I just add functions when i need them.
It is also designed to make python more friendly to users of other languages (Eg, arduino IDE (Delay(time in milliseconds)))
I hope that someone can make use of at least half of these functions.

This is supposed to be imported using

From module_name import *
import serial,time,textwrap,smtplib,random,os,math

def chipReset(port,baudrate):
    try:
        serial.Serial(port, baudrate)
        return 1
    except:
        return 0
    
def chipTalk(port,baudrate,Data_out,timer):
    try:
        ser = serial.Serial(port, baudrate)
        delay(timer)
        ser.write(Data_out)
        return 1
    except:
        return 0
        
def chipRead():
    try:
        complete = ""
        info = ser.read()
        
        if (info != "EOL"):
            if (info != "0"):
                complete = complete + info;
            else:
                return complete
        else:
            return complete
        if ((ser.available())==False):
            return complete
        chipRead()
    except:
        return 0

def writeToFile(Filename,Data):
    try:
        file = open(Filename,'w')
        file.write(Data)
        file.close
        return 1
    except:
        return 0

def ReadFromFile(Filename):
    try:
        file = open(Filename,'r')
        data = file.read()
        file.close
        return data
    except:
        return 0

def appendFile(append,Filename):
    try:
        file = open(Filename,'r')
        data = file.read()
        file.close
        
        data = data + append
        
        file = open(Filename,'w')
        file.write(data)
        file.close
        return 1
    except:
        return 0

def deleteFile(FileName):
    try:
        os.remove(FileName)
        return 1
    except:
        return 0

def isEven(number):
    if (number % 2 == 0):
        return True
    else:
        return False

def isPrime(x):
    return all(x % i for i in range(2, x))

def wait(x):
    time.sleep(x)
    return

def pause(x):
    x = x / 1000
    time.sleep(x)
    return

def delay(x):
    time.sleep(x/1000)
    return

def send_email(GMAIL_USERNAME,GMAIL_PASSWORD,SUBJECT,TEXT):
    
    try:
        smtpserver = smtplib.SMTP("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo()
        smtpserver.login(GMAIL_USERNAME, GMAIL_PASSWORD)
        header = '\tTo:' + GMAIL_USERNAME + '\n\t' + 'From: ' + GMAIL_USERNAME
        header = header + '\n\t' + 'Subject:' + SUBJECT + '\t\n'
        msg = header + '\t\n' + TEXT + ' \n\n'
        smtpserver.sendmail(GMAIL_USERNAME, GMAIL_USERNAME, msg)
        smtpserver.close()
        return 1
    except:
        return 0

def randomFloat(range1,range2):
    result = random.uniform(range1.range2)
    return result

def randomChoice(selection):
    result = random.choice(selection)
    return result

def randomSample(selection,amount):
    result = random.sample(selection,amount)
    return result

def randomNormalVariate(mean, sdev):
    result = random.normalvariate(mean, sdev)
    return resul

def TrigUnknownHypotenuse(sideA,sideB):
    result = math.sqrt((sideA * sideA) + (sideB * sideB))
    return result

def TrigKnownHypotenuse(side,hyp):
    result = math.sqrt((hyp * hyp) - (side * side))
    return result

def perimeter(sideA,sideB):
    result = (2 * sideA) + (2 * sideB)
    return result

def area(sideA,sideB):
    result = sideA * sideB
    return result

def fibonacciSet(x):
    result = []
    def fib():
        a, b = 0, 1
        while True:            # First iteration:
            yield a            # yield 0 to start with and then
            a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)

    for index, fibonacci_number in enumerate(fib()):
        result.append(fibonacci_number)
        if index == x:
            break
    return result

def fibonacciSingular(x):
    result = 0
    def fib():
        a, b = 0, 1
        while True:            # First iteration:
            yield a            # yield 0 to start with and then
            a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)

    for index, fibonacci_number in enumerate(fib()):
        if index == x:
            result = fibonacci_number
            break
    return result

def password(password,clear,alreadySet):
    message = ""
    password2 = password
    file = open("Password.EncodedSafe","r")
    if (file.read(1) == "T"):
        alreadySet = "T" + file.read(3)
    else:
        alreadySet = "F" + file.read(4)
    unit = file.read()
    file.close()

    if (alreadySet == "True"):
        if(password == unit):
            if(clear == True):
                alreadySet = "False"
                file = open("Password.EncodedSafe","w")
                file.write("")
                file.close()
                return "3 - Password Cleared"
            else:
                return "1 - Correct"
        else:
            return "4 - Incorrect"
    else:
        unit = password
        alreadySet = "True"
        file = open("Password.EncodedSafe","w")
        message = alreadySet + unit
        file.write(message)
        file.close()
        return "2 - Password set"
    
    if(password2 == unit):
        if(clear == True):
            alreadySet = "False"
            file = open("Password.EncodedSafe","w")
            file.write("")
            file.close()
            return "3 - Password Cleared"
    else:
        return "4 - Incorrect"
    
def CelsiusToFahrenheit(x):
    x = x * (9/5) + 32
    return x

def FahrenheitToCelsius(x):
    x = (x - 32) * (5/9)
    return x

def CelsiusToKelvin(x):
    x = x + 273.15
    return x

def KelvinToCelsius(x):
    x = x - 273.15
    return x

def FahrenheitToKelvin(x):
    x = (FahrenheitToCelsius(x)) + 273.15
    return x

def KelvinToFahrenheit(x):
    x = (FahrenheitToCelsius(x)) - 273.15
    return x

def cosD(x,decimalPlaces):
    x = math.cos(math.radians(x))
    x = round(x,decimalPlaces)
    return x

def sinD(x,decimalPlaces):
    x = math.sin(math.radians(x))
    x = round(x,decimalPlaces)
    return x

def tanD(x,decimalPlaces):
    x = math.tan(math.radians(x))
    x = round(x,decimalPlaces)
    return x

def keyCont():
    random_Unused_Variable = input()
    return

If you have any other suggestions for functions, please comment as i am certain that there are some crucial ones that i have missed out.
PS, if anyone has a solution to stop chipTalk(port,baudrate,Data_out,timer) from reinitialising the arduino everytime it is called, I would be very thankful.
Quote
#2
Trying to be constructive here, but your script really kind of serves as a guide on "what not to do".

Let's start with:
Quote:This is supposed to be imported using

From module_name import *
No, your module is not special.  Star imports are bad.  This is no exception.  The only place that is really an exception is in an __init__.py file of a package.  Also you capitalized from so it won't even work.


Next let's move on to your exceptions.

Quote:
try:
    # do something
    return 1
except:
    # on failure
    return 0
This is very bad.  Firstly in general when we use exceptions you want to catch a specific exception so when your program fails you know why.

Take this function for example:
Quote:
def ReadFromFile(Filename):
    try:
        file = open(Filename,'r')
        data = file.read()
        file.close
        return data
    except:
        return 0
You have taken some file operations which already return meaningful exceptions and completely silenced them.

Watch what happens when I try to open a file for reading that doesn't exist:
>>> f = open("Somefile")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'Somefile'
>>>
The programmer is told exactly what the problem is.  Very clear and informative.  A person who uses your module does not get this information and needs to look for the source of the issue.  Also, you never actually closed the file (you forgot the parenthesis; it should read file.close()).  To go even further you should be using with rather than explicitly needing to close.

Moving on, another issue you have is redefining functions which already do exactly what you are asking.   Basically you are taking a known library function people may be familiar and just replacing it with your own name:

Quote:
def wait(x):
    time.sleep(x)
    return
in this case just use time.sleep.  You are only obfuscating things by doing this. Same goes for all your random functions.

Now to your rounding functions.  I think you are misunderstanding something fundamental here.  You generally don't want to round the actual number.  What you want is to change how it is displayed.  Creating trig versions that round things is just strange.

What you would do in general usage is use the given function, and then when printing it specify the decimal places you want to see.
>>> import math
>>> val = math.tan(5.64)
>>> val
-0.7495066768063932
>>> print("{:.2}".format(val))
-0.75
>>> val
-0.7495066768063932
>>>
This way if you want to continue using a value it loses no precision.  Also, I know we tend to have more intuitions about angles in degrees in daily life but in a mathematical context (and especially considering trigonometry) radians really are more natural and intuitive.

Next, returning a boolean expression directly.
Quote:
def isEven(number):
    if (number % 2 == 0):
        return True
    else:
        return False
This is common with newcomers but what you want is to just return the expression directly:
def is_even(number):
    return number % 2 == 0
Anyway, I will leave it at that for the moment.
I know a lot of this probably sounds very harsh but hopefully you can see the benefit in some of it.
buran and metulburr like this post
Quote
#3
wait = time.sleep will do exactly the same
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)