import sys
e = input("Do you want to continue?(Enter Y or N)?")
if e == "Y":
sys.exit()
I'm trying to create an exit function that allows the user to exit. Am I using the wrong format or did I mess up the syntax ?
Try this code:
import sys
e = input("Do you want to continue?(Enter Y or N)?")
if e == "Y":
sys.exit()
There was an indentation problem and you were missing a :
Also, I'd like to recommend using this logic also:
import sys
e = input("Do you want to continue?(Enter Y or N)?")
if e.lower() in {'y','yes'}:
sys.exit()
This will provide more flexibility since it will accept Y, y and different versions of yes.
Related
I'm running the following code in Python 3.7 using Spyder 3.3.2.
If i run the code manualy (ie: in Spyder Editor I select the library import en press "F9", then I select the function I want to run and press "F9") it works.
But if I press "Play" in the tool bar to run the complet file it doesn't work, and I get :
BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending
I'm aware of the problem in Spyder and i'm already running in the current WD. I've also used the trick of the if __name__ = __main__: to run my function as main().
The code I'm building is intended to be used by people not familiar with programming, so for them it's much safer to click "Play" than to select and run specific bite of code.
Here's the code, the content of the function doesn't seem to be a problem and paralellize well when working, using 100% of the 8 cores.
If it helps, the biggest file imported is less than 1mb.
from concurrent.futures import ProcessPoolExecutor
import pandas as pd
import numpy as np
from MPO_PROC import N_tab, N_tab_FCT, TYPE, TR
from MPO_FUNC import *
def main():
""" Set the variables for the loop """
alpha = 0.05
alg_type = TYPE
futures = []
e = ProcessPoolExecutor(8)
if alg_type == "O":
F = FFR_ME
elif alg_type == "NO":
F = FFR_ME_NO
else :
raise TypeError("Algortithm type selected does not exist. Must be 'O' or 'NO'")
""" Loop over the different task summarized in the tab 'N_tab' during the MPO_PROC step. """
for task in N_tab["TASK_NUMBER"]:
""" Declare variables N, n , f based on the previous calculations """
N = N_tab_FCT.loc[N_tab_FCT["TASK_NUMBER"] == task, "N_Task"]
n = N_tab_FCT.loc[N_tab_FCT["TASK_NUMBER"] == task, "n_i"]
f = N_tab_FCT.loc[N_tab_FCT["TASK_NUMBER"] == task, "F"]
"""" Implement the function using the concurrent.future module for multiprocessing. """
for Ni, ni, fi in zip(N,n,f):
future = e.submit(F, Ni, ni, fi, alpha)
futures.append(future)
results = [ff.result() for ff in futures]
for i in range(len(results)):
f = int(N_tab_FCT.loc[i, "F"])
N_tab_FCT.loc[i,"LBound"] = results[i][0][f]
N_tab_FCT.loc[i,"UBound"] = results[i][1][f]
N_tab_FCT.loc[i,"ME"] = (N_tab_FCT.loc[i,"UBound"] - N_tab_FCT.loc[i,"LBound"])/\
(2*N_tab_FCT.loc[i,"N_Task"])
N_tab_FCT.loc[i,"FFR"] = (N_tab_FCT.loc[i,"LBound"] + (N_tab_FCT.loc[i,"UBound"] - N_tab_FCT.loc[i,"LBound"])/2)/\
N_tab_FCT.loc[i,"N_Task"]
if __name__ == "__main__":
main()
Thank you.
I have a function in my code that asks the user for input:
def function_1():
...
x = input('Please provide input')
...
return something
I want to be able to run my code, and when the program eventually reaches function_1 and asks the user for input, automatically provide it with some specified input. When unittesting, I can use the mock library to simulate keyboard input as below
#mock.patch('builtins.input', side_effects=[1,2,3])
function_1()
function_1()
function_1()
This calls the function three times and provides the inputs {1, 2, 3}. I'm wondering if there is a way to do the same thing outside of unittesting.
I'm aware that I can rewrite the code, or use pipe in terminal. But I'm more curious about whether this can be solved in the manner described above.
One way is to overwrite sys.stdin:
import sys
from io import StringIO
oldstdin = sys.stdin
sys.stdin = StringIO("1\n2\n3\n")
assert input() == "1"
assert input() == "2"
assert input() == "3"
sys.stdin = oldstdin
The great thing about Python is that you can override just about any function, even built-ins.
def override():
from itertools import count
counter = count()
return lambda *args, **kwargs: next(counter)
input = override()
def x():
return input("Testing123")
print(x()) # 1
print(x()) # 2
print(x()) # 3
Though, this has to be done before your functions are called.
I have two files. The first file, we'll call it "a.py". The second, "b.py".
Here's an example of "a.py":
#!/usr/bin/env python
# coding=utf-8
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
a = 666
b = "bbb"
def f():
print("this is a test")
return "function"
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Here's an example of "b.py":
#!/usr/bin/env python
# coding=utf-8
import a
from a import b,f,CHOOSE,username
a = a.a
f()
print(b,a,CHOOSE,username)
when i run python b.py,system feedback error:
wherem am i wrong?how to fix it?
Because this snippet:
if __name__ == '__main__':
if CHOOSE == '1':
username = 'tom'
print(username)
elif CHOOSE == '2':
username = 'jack'
print(username)
else:
print('wrong choice,scipt is exit...')
Will get executed only if the a.py run as the main python file not imported from other module, so username will not be defined so you can not import it. Here how to fix it:
a.py:
...
def foo(CHOOSE):
if CHOOSE == '1':
username = 'tom'
elif CHOOSE == '2':
username = 'jack'
else:
username = None
return username
b.py:
from a import foo
CHOOSE = input ('''
\033[1;35m choose 1 or 2:\033[0m
1)tom
2)jack
''')
username = foo(CHOOSE)
if username:
print(username)
else:
print('Wrong choice')
Explanation: First you need to extract the code that calculate the name into something reusable. Function are meant for code reusability so I defined one which take one parameter and it return the corresponding value. This function is then used (imported then invoked) in b.py.
Usually if __name__ == '__main__': is placed in the module that you consider your entry-point, so if you want to use it maybe b.py is a better place.
The block if __name__ == '__main__' only triggers if the script is run with a.py being the main module (e.g. you ran it using the command python a.py). If anything else was used as the main module, and a was imported, then this condition is not met and the code inside of it does not run.
The variable username is created and added to a's namespace in the if __name__ == '__main__' block. When you do python b.py, the code inside this block does not execute, and as a result username never gets added to the namespace. So when you try to import it, immediately after loading the file a, you get an error saying that the 'username' doesn't exist - it was never created.
I have a function called learn in a module called lrn_proto.
I use it at other script, I can import it, but I'm not able to use it's function, it works before. But right now its not working anymore, and I even didn't modify the source code.
Here is the source of lrn_proto:
import sys
import os
import re
import time
sys.path.append(os.path.abspath('..\\..\\..\\conf'))
sys.path.append(os.path.abspath('..\\..\\writer\\mem_writer_proto'))
from cfg_exe import exe_loc as loc
sys.path.append(os.path.abspath(loc.lib))
sys.path.append(os.path.abspath(loc.mem))
sys.path.append(os.path.abspath(loc.main))
import mem_writer as mw
import prototype_ui as ptui
def learn(src,keywords,type,identifier):
if src == r'\exit':
print('You have choose to exit this program, see you later.')
sys.exit()
elif src == r'\add':
ptui.menu()
temp = src.lower()
for x in keywords:
if x in temp:
temp_k1 = list(temp.partition(x))
try:
temp_k1_t = list(str(temp_k1.index(x)))
except ValueError:
pass
for b in temp_k1_t:
temp_k = list([temp_k1.pop(int(b))])
print('True\n')
continue
elif x not in temp:
temp_k = list('')
pass
for x in type:
if x in temp:
temp_t1 = list(temp.partition(x))
try:
temp_t1_t = list(str(temp_t1.index(x)))
except ValueError:
pass
for b in temp_t1_t:
temp_t = list([temp_t1.pop(int(b))])
print('True\n')
continue
elif x not in temp:
temp_t = list('')
pass
for x in identifier:
if x in temp:
temp_i1 = list(temp.partition(x))
try:
temp_i1_t = list(str(temp_i1.index(x)))
except ValueError:
pass
for b in temp_i1_t:
temp_i = list([temp_i1.pop(int(b))])
print('True\n')
continue
elif x not in temp:
temp_i = list('')
pass
temp_kti = list(temp_k+temp_t+temp_i)
act_patt = '|'.join(temp_kti)
act = (''.join((re.split(act_patt,temp))).strip(' .'))
print('Output:')
print('Keywords: ',temp_k,'\nType: ',temp_t,'\nIdentifier: ',temp_i,'\nContent: ',act)
mw.dict(title,type,keywords,identifier,actions)
I tried:
from lrn_proto import learn
It produce:
ImportError: cannot import name 'learn' from 'lrn_proto'
Then with
import lrn_proto,
It produce this while the function is being called:
AttributeError: module 'lrn_proto' has no attribute 'learn'
The weird things are Those produced error doesn't tell me whats wrong with my code.
I had already add all modules directory to sys.path
Did anyone can inform me what is the wrong of my code?
I had no idea about what's wrong with my code.
I'm using Python3 on Windows.
Kindly ask me if you need more info about this question.
I am very beginner on Python and I want to create crossworld template, like this. How can I create gui exactly like this on python ? Are there any tools or libraries ? I made lots of research but ı could not find anything.
Thanks!!!
Since you're a beginner, try out PySimpleGUI.
Here's a little program to get you started...
import sys
if sys.version_info[0] >= 3:
import PySimpleGUI as sg
else:
import PySimpleGUI27 as sg
import random
BOX_SIZE = 25
layout = [
[sg.Text('Crossword Puzzle Using PySimpleGUI'), sg.Text('', key='_OUTPUT_')],
[sg.Graph((800,800), (0,450), (450,0), key='_GRAPH_')],
[sg.Button('Show'), sg.Button('Exit')]
]
window = sg.Window('Window Title').Layout(layout).Finalize()
g = window.FindElement('_GRAPH_')
for row in range(16):
for i in range(16):
if random.randint(0,100) > 10:
g.DrawRectangle((i*BOX_SIZE+5,row*BOX_SIZE+3), (i*BOX_SIZE+BOX_SIZE+5,row*BOX_SIZE+BOX_SIZE+3), line_color='black')
else:
g.DrawRectangle((i*BOX_SIZE+5,row*BOX_SIZE+3), (i*BOX_SIZE+BOX_SIZE+5,row*BOX_SIZE+BOX_SIZE+3), line_color='black', fill_color='black')
g.DrawText('{}'.format(row*6+i+1),(i*BOX_SIZE+10,row*BOX_SIZE+8))
while True: # Event Loop
event, values = window.Read()
print(event, values)
if event is None or event == 'Exit':
break
window.Close()