How to gracefully exit from ipython script on jupyter notebook - jupyter-notebook

I am new at coding. I am working on jupyter notebook using anaconda environment. I have this sample code where I am using sys.exit() command. When it gets executed it exits script with several error messages. Here is my sample code.
import sys
name = 'joh'
if name == 'john':
print('Name matches')
else:
print('Incorrect name')
sys.exit(0)
... some more code
Upon execution, it returns
Incorrect name
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
C:\Users\ankur.kulshrestha\AppData\Local\Continuum\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2889: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
How can I gracefully exit the script without receiving all these error messages (apart from the first line which I have actually put in the code.)

Related

How to quit R script when an error occurred

I am writing an R script as a command to run in terminal, and I found if an error happen when running this script, the command still returns a normal exit signal. So I cannot check the running results by checking [ $? -ne 0 ], it just returns succeed.
This is because R will continue running the next command when it encounters an error in previous command. Is there any way to solve this situation?
Best,
Shixiang
I combine tryCatch() and quit() to solve this problem. I firstly wrap my main function to tryCatch structure to let it detect if an error occurred, once an error is detected, I print the error message and call quit("no", -1) to quit R with exit status signature -1.

Spyder debugger causes deep recursion

I am trying to debug a script using spyder debugger. When entering debugger mode, python return the following error :
RecursionError: maximum recursion depth exceeded
My code does not use recursion. However, going up the traceback I see it is actually spyder's debugger pdb that triggers the recursion given that I see a bunch of the following repeated many times :
File "C:\Users\XXXX\Documents\PythonEnvs\Python36Main\lib\site-packages\pdb.py", line 169, in __init__
super(Pdb, self).__init__(*args, **kwargs)
File "C:\Users\XXXX\Documents\PythonEnvs\Python36Main\lib\site-packages\IPython\core\debugger.py", line 232, in __init__
OldPdb.__init__(self, completekey, stdin, stdout)
Any idea what is going on ? I tried on the machine of a colleague who is running 3.7 and he can debug without any issue.
EDIT : To the request, I tried a really simple script as shown herebelow :
def simpleFunction():
print("this is a simple function")
Entering the debug on this simple script triggers the same issue. Note that before, I could run the debugger without problem. I do not know what has changed since then.

Errors while using asyncio in Python 3.6 to execute terminal commands

I am using asyncio for the first time and I am getting these two errors:
1) RuntimeError: set_wakeup_fd only works in main thread
2) RuntimeError: Cannot add child handler, the child watcher does not have a loop attached
Usage scenario:
I have to execute two terminal commands, one followed by another. To ensure the second command gets executed only after the first, I'm using asyncio to set the loops and running them.
I am trying to execute a function in this python file using a flask api ultimately.
Has someone come across these errors and can guide me to resolve it?
Any help would be great!
Code:
async def segmentVide(command):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
asyncio.get_child_watcher()
return stdout.decode().strip()
def segmentOutput(folderCreated):
#command = MP4Box terminal command
loop = asyncio.new_event_loop()
asyncio.get_child_watcher().attach_loop(loop)
asyncio.set_event_loop(loop)
coro = loop.run_in_executor(None, segmentVide, command)
loop.run_until_complete(coro)
loop.close()
print('completed')
There is another function executing the other terminal command but the asyncio usage part is the same in it too.

Why the imported PowerFactory module in python can only execute single time?

The script is be able to run a software called PoiwerFctory externally by Python as follows:
#add powerfactory.pyd path to python path
import sys
sys.path.append("C:\\Program Files\\DIgSILENT\\PowerFactory 2017
SP2\\Python\\3.6")
#import powerfactory module
import powerfactory
#start powerfactory module in unattended mode (engine mode)
app=powerfactory.GetApplication()
#get the user
user=app.GetCurrentUser()
#active project
project=app.ActivateProject('Python Test') #active project "Python Test"
prj=app.GetActiveProject #returns the actived project
#run python code below
ldf=app.GetFromStudyCase('ComLdf') #caling loadflow command object
ldf.Execute() #executing the load flow command
#get the list of lines contained in the project
Lines=app.GetCalcRelevantObjects('*.ElmLne') #returns all relevant objects,
i.e. all lines
for line in Lines: #get each element out of list
name=line.loc_name #get name of the line
value=line.GetAttribute('c:loading') # return the value of elements
#Print the results
print('Loading of the line: %s = %.2f'%(name,value))
When the above code first time executed in Spyder, it will show proper resutls. However, if re-executing the script again, the following error is appeared:
Reloaded modules: powerfactory
Traceback (most recent call last):
File "<ipython-input-9-ae989570f05f>", line 1, in <module>
runfile('C:/Users/zd1n14/Desktop/Python Test/Call Digsilent in
Python.py', wdir='C:/Users/zd1n14/Desktop/Python Test')
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/zd1n14/Desktop/Python Test/Call Digsilent in Python.py",
line 12, in <module>
user=app.GetCurrentUser()
RuntimeError: 'powerfactory.Application' already deleted
Referred to How can I exit powerfactory using Python in Unattended mode?, this may because of PowerFactory in still running. And the only way which has been found so far is to re-start the Spyder and execute the script again, this is so inefficiency that if I want to re-write the code and debugging it.
It would be so much appropriated that if anyone could give me some advice for such problem.
I ran into the same Problem. Python is still connected to powerfactory and gives the Error if you try to connect again. What basicly worked for me was to kill the instance on the end of your skript with
del app
another idea during debugging could be:
try:
# Do something in your skript
finally:
del app
So the killing of the instance happens in any case.
The way to solve this is to reload the powerfacotry module by adding:
if __name__ == "__main__":
before import powerfacory.
The reason behind may referred to: What does if __name__ == "__main__": do?.

Disable the error message (failed to execute script) obtained with pyinstaller

Hi how do I disable the error (failed to execute script) when i run a exe process created with pyintaller ? without fix the script , because the script works well
"failed to execute script" says that your python program terminates with non-zero exit code by exception.
Try this:
import sys
def my_except_hook(exctype, value, traceback):
sys.exit(0)
return
sys.excepthook = my_except_hook

Resources