Exiting interactive python3 session from script - python

I'd like my program to automatically exit if it detects an error when loading a file and parsing it (even when called from an interactive mode with -i). I've tried variations of exit() and sys.exit(), but nothing seems to be working. Instead of exiting the interactive session I get a stack trace. For example, if I have the file test.py that is the following:
import sys
sys.exit(0)
when I run python3 -i test.py I get the following result:
Traceback (most recent call last):
File "test.py", line 2, in <module>
sys.exit()
SystemExit
>>>
and the session continues on, until I exit myself (using those exact lines subsequently work, just not when they're called from the script). What am I missing?

Try calling os._exit() to exit directly, without throwing an exception
import os
os._exit(1)
Note that this will bypass all of the python shutdown logic.
Hope it helps.

Related

Python shell execution programatically

I have a requirement to run python commands at run on shell programmatically, its almost replicating REPL but programmatically, I tried below code which worked for the first line but it's not carrying the session the way CLI does, kindly help
import subprocess as s
import sys
res=s.run([sys.executable, "-c", "a=5"])
s.run([sys.executable, "-c", "print(a)"])
Error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'a' is not defined
I am getting the error as those 2 commands are being executed in 2 different processes, is there any way to run in one process but in different lines(Similar to what we do in python interpreter(REPL)), I am working on the requirement to capture python commands from some external files and run them on the shell, so I won't know what command I will be executed until it actually appears in an external file.
[![enter image description here][2]][2]
You can use Popen of subprocess. stdin is waiting your commands.
import subprocess as s
import sys
res=s.Popen(sys.executable, stdin=s.PIPE)
res.stdin.write(b"a=5\n")
res.stdin.write(b"print(a)")

Python: How to prompt console input when stdin is occupied?

In an Ubuntu environment, I am hosting a script on a web server and I'm trying to run the script without writing it to a file using the line wget -O - -o /dev/null 0.0.0.0:8000/myscript | python
The script starts off running just fine, until I get to a use of input() where I get this error
Traceback (most recent call last):
File "<stdin>", line 629, in <module>
EOFError: EOF when reading a line
I did a little reading on sys.stdin but I'm not finding a clear solution. What can exactly is happening here and how can I work around it?
Found the solution here: Pipe input to Python program and later get input from user
I added the line sys.stdin = open("/dev/tty") and now it seems to work.

Why does PyCharm try to reacquire stdin upon termination?

MCVE:
import threading
threading.Thread(target=input, daemon=True).start()
If you run the above as a script in PyCharm with the default run configuration (without entering any input), you get the following fatal error when the program terminates:
Fatal Python error: could not acquire lock for <_io.BufferedReader name='<stdin>'> at interpreter shutdown, possibly due to daemon threads
Python runtime state: finalizing (tstate=00000200EF89E1C0)
Thread 0x0000459c (most recent call first):
File "C:\Program Files\Python38\lib\threading.py", line 870 in run
File "C:\Program Files\Python38\lib\threading.py", line 932 in _bootstrap_inner
File "C:\Program Files\Python38\lib\threading.py", line 890 in _bootstrap
Current thread 0x00001b78 (most recent call first):
<no Python frame>
But if you run this from the terminal with python script.py or check the "Emulate terminal in output console" in PyCharm for this run configuration, no such error occurs.
As far as I understand, the error happens because when input is called, it suspends the thread indeterminately until input returns (and there's no way of interrupting this), blocking stdin during this time, so when the main thread terminates, since the other thread is a daemon, Python starts finalization, and when it tries to reacquire the lock for stdin, it can't because it is still locked by the input call.
But the question is, why does it make a difference whether it is run in PyCharm's output console vs a terminal/terminal emulator? Does the terminal make Python not try to reacquire the lock? Or does the error still occur but it gets silenced for some reason? Or what?
If case this helps, in CPython, this error is raised in the _enter_buffered_busy function in bufferedio.c.
UPDATE: I've filed a ticket on PyCharm's issue tracker.

NameError: name 'runfile' is not defined only when running from script

sima.py
import pyautogui as py
py.alert("Foo")
simaref.py
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py',
wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
These both work when running from Spyder.
sima.py works from cmd as well:
python.exe E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\sima.py
But simaref.py doesn't:
E:\Download\PROGIK\ANACONDA>python.exe E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\simaref.py
Traceback (most recent call last):
File "E:\Anyagok\Programozas\Python\projekts\gyak\Pyautogui\simaref.py", line 8, in <module>
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py', wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
NameError: name 'runfile' is not defined
Why not?
Edit:
Got the idea of runfile() from: when running code in Spyder, in the console it displays e.g.:
runfile('E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/simaref.py', wdir='E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui')
Working with roganjosh's answer:
Couldn't find where to import the runfile() command, maybe it's something built-in. So I changed simaref.py to the code below, and now it works.
exec(open("E:/Anyagok/Programozas/Python/projekts/gyak/Pyautogui/sima.py").read())

I am trying to make a .app for my test first python script using playpus

This is my script
removed
it works fine through terminal but when i make it a .app with Platypus i get this when running the app
Hello How are you?
Traceback (most recent call last):
File "/Users/shameer/Desktop/Test Programs/questions.app/Contents/Resources/script", line 2, in <module>
feeling = raw_input()
EOFError: EOF when reading a line
Platypus doesn't create an interactive terminal session, it just pipes your script output into a textfield. You won't be able to wrap interactive programs with it.

Categories