from math import *
def solution_handler(self, input):
while re.search(r'(?<!\.)(\d+)(?!\.)(\d*)', input):
rx = re.search(r'(?<!\.)(\d+)(?!\.)(\d*)', input)
input = input[:rx.start()] + rx.group() + ".0" + input[rx.end():]
exec "solution = " + input
return solution
This is the code that I'm using to solve the equations entered into the calculator I'm working on. It seems to work fine most of the time, but if I try to enter a function (cos, sin, etc.) with a value outside of [-9,9], the program freezes.
What did I do wrong?
Example strings:
exec "solution = " + "6*cos(6)" -> solution = 5.761 ...
exec "solution = " + "7/cos(8/2)" -> solution = -10.709 ...
exec "solution = " + "sin(12) + 3" -> Freeze
exec "solution = " + "abs(-50) / 2" -> Freeze
It seems to be the case with any function that I try to use.
The problem is with your loop: remove the exec and it would still hang. Try this instead:
from __future__ import division
from math import *
def solution_handler(self, input):
return eval(input)
Related
I'm trying to use the input function but every time, without fail, the word "None" appears at the end of my question/string (well running), it's capitalized just like that but has no overall effect on the code, it just ruins the project I'm working on.
Here's my code:
import time
import sys
def dp(s):
for c in s:
if c != " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.22)
elif c == " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0)
name = input(dp("Hello, whats your name? "))
Every function in python will return something, and if that something isn't defined it will be None (you can also explicitly return None in a function). So, your dp() function returns None, and so you are effectively calling input(None), which gives the same prompt of None.
Instead, try putting in input() call within the function itself.
def dp(s):
for c in s:
if c != " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.22)
elif c == " ":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0)
return input()
name = dp("Hello, whats your name? ")
So i am creating a slot machine as a little project for fun and learning, I was wondering if there was a way to replace multiple lines of text in the console. I have it replacing one line but I would like to be able to print three lines then the top be replaced with the middle then middle with the bottom and continue untill the loop is finished. I am still a beginner so if there are any tips you have for me and or please feel free to critique my code. Thank you
import sys
import time
from random import randint
slot_possibilities = [" Star "," Moon "," Sun! "," Monkey"]
wait_time = 15
print "--------------------------------"
print "|--------Monkey-----Slots------|"
print "|------------------------------|"
while wait_time != 0 :
x = randint(0,3)
y = randint(0,3)
z = randint(0,3)
sys.stdout.write("\r|" + slot_possibilities[x] + " || " + slot_possibilities[y] + " || "+ slot_possibilities[z] + " |")
time.sleep(1)
wait_time -= 1
print
print
I need to run programs parallel, 3 at a time. I tried the following but when programC finished before A and B, it does not work. How can I limit the number of running programs to, say, at most 3 at any time.
for i in range(10):
os.system("xterm -e program " + i + "a" + " &")
os.system("xterm -e program " + i + "b" + " &")
os.system("xterm -e program " + i + "c" + " ")
Here my solution, though I will select a better answer:
for i in range(10):
a = subprocess.Popen(["xterm -e program"+ i + " a" ],shell=True)
b = subprocess.Popen(["xterm","-e","program",i," b"])
c = subprocess.Popen(["xterm","-e","program",i," c"])
a.wait()
b.wait()
c.wait()
I would like show progress to user when my python script processing a big file.
I have seen script printings '\', "|', '/' in the same cursor position in the shell to show progress.
How can I do that in python?
You should use python-progressbar
It's as simple to use as:
import progressbar as pb
progress = pb.ProgressBar(widgets=_widgets, maxval = 500000).start()
progvar = 0
for i in range(500000):
# Your code here
progress.update(progvar + 1)
progvar += 1
This will show a progress bar like:
Progress: |#################################################### |70%
A simple "infinite spinner" implementation:
import time
import itertools
for c in itertools.cycle('/-\|'):
print(c, end = '\r')
time.sleep(0.2)
tqdm is a more powerful one for this case. it has better features and comparability.
it is easy for usage, the code could be simple as:
from tqdm import tqdm
for i in tqdm(range(10000)):
pass # or do something else
customization is also easy for special cases.
here is a demo from the repo:
If you want to roll your own, you can do something like this:
import sys, time
for i in range(10):
print ".", # <- no newline
sys.stdout.flush() #<- makes python print it anyway
time.sleep(1)
print "done!"
This'll print one dot every second and then print "done!"
Or the usual helicopter (in Python 3):
import sys, time
for i in range(10):
print("/-\|"[i % 4], end="\b")
sys.stdout.flush() #<- makes python print it anyway
time.sleep(0.1)
print("\ndone!")
Made this for fun. It shows the spinning bar and the text loading. Like this:
|
\ l
- lo
/ loa
| load
\ loadi
- loadin
/ loading
The code was tested on windows.
'''
Spinner and a text showing loading.
'''
import sys
import time
def looper(text):
sys.stdout.write('\r')
sys.stdout.write(text)
sys.stdout.flush()
spinner = ["|", "\\" , "-", "/" ]
loading = ['l','o','a','d','i','n','g']
spin_1 = len(spinner)
spin_2 = len(loading) + 1
print("Starting program...")
for x in range(100):
spin_2mod = x%spin_2
looper(spinner[x%spin_1] + " " + "".join(loading[0: (spin_2mod) ]) + (" " * (spin_2 - spin_2mod)))
time.sleep(0.5)
print("\nExiting program...")
time.sleep(2)
This code works for me:
class ProgressBar(object):
def __init__(self, maxval=100):
self.currval = 0
self.maxval = int(maxval)
self.last_progress = 0
sys.stdout.write("0")
sys.stdout.flush()
def next(self, val = None):
if val:
self.currval = val
else:
self.currval = self.currval + 1
progress = round(20 * self.currval / self.maxval)
while self.last_progress < progress:
self.last_progress = self.last_progress + 1
self._print_progress(self.last_progress)
def finish(self):
while self.last_progress < 20:
self.last_progress = self.last_progress + 1
self._print_progress(self.last_progress)
sys.stdout.write("\n")
sys.stdout.flush()
def _print_progress(self, progress):
if progress % 5 == 0:
percent = int(progress * 5)
sys.stdout.write(str(percent))
else:
sys.stdout.write(".")
sys.stdout.flush()
This code works well with large amount of iterations like hundreds of millions - it doesn't redraw console on every iteration.
Use sample:
progress = ProgressBar(band.YSize)
for y in xrange(0, band.YSize, 256):
array = band.ReadAsArray(x, y, 256, 256)
map_array_values(array, values)
progress.next(y)
del array
progress.finish()
It will display progress in GDAL style:
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python Application does nothing
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv("HOSTNAME")
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
The input() is supposed to execute and it stopped working after changing something I dont remember
It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong
I know userinput does nothing, I want to get this part working before I continue on
Thanks
It outputs nothing
You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end?
I think you need a call to MainShellLoop.