473,322 Members | 1,690 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

How to tell if I'm being run from a shell or a module

Hi all,

Is there any standard way to tell if the user is running from a module
or from an interactive shell like IDLE or IPython? The best I've come
up with so far is for a function to look at
getouterframes(currentframe())[1][1] (the filename in the frame record
of the frame that called the function), and check if it exists or not
with os.path.exists. IPython gives '(ipython console)' and IDLE gives
'pyshell#0' whereas running from a module gives its filename. This
seems a bit hacky. Any better ideas?

--
Dan Goodman
http://thesamovar.net/contact
Feb 14 '08 #1
5 1800
Conventionally, you use:

if __name__ == '__main__':
# do something as a script
Feb 14 '08 #2
On Feb 14, 7:21 pm, dg.google.gro...@thesamovar.net wrote:
Hi all,

Is there any standard way to tell if the user is running from a module
or from an interactive shell like IDLE or IPython? The best I've come
up with so far is for a function to look at
getouterframes(currentframe())[1][1] (the filename in the frame record
of the frame that called the function), and check if it exists or not
with os.path.exists. IPython gives '(ipython console)' and IDLE gives
'pyshell#0' whereas running from a module gives its filename. This
seems a bit hacky. Any better ideas?

--
Dan Goodmanhttp://thesamovar.net/contact
If you're just trying to prevent some actions from happening if
something loads your script as a module just put the 'action items'
under an if like:
if __name__ == '__main__':
do_the_cool_stuff()

All your functions inside the file will remain in-tact but it won't
execute anything.
Feb 14 '08 #3
Thanks for the replies, but it's not what I meant. What I want to be
able to determine is whether or not the user is running from an
interactive shell (like IPython or IDLE). Checking if
__name__=='__main__' checks if the current module is the one being
run, but suppose you have two modules A and B, with the function f
defined in module B that should print 'Interactive' or 'Module' say.
The module A just consists of: import B; B.f(). Now whenever f is
called, __name__ will not be '__main__' for it. Someone using IDLE
could write import B then B.f() too. The question is: is there a way
for f to determine if someone was using an interactive shell to call
it or if it was being called some other way. The way I came up with
works in these limited cases but won't work in a more general
situation (but perhaps there is no way for it to know in the more
general situation).

Dan

On Feb 14, 7:01 pm, Chris <cwi...@gmail.comwrote:
If you're just trying to prevent some actions from happening if
something loads your script as a module just put the 'action items'
under an if like:
if __name__ == '__main__':
do_the_cool_stuff()

All your functions inside the file will remain in-tact but it won't
execute anything.
Feb 14 '08 #4
En Thu, 14 Feb 2008 19:09:10 -0200, <dg**************@thesamovar.net>
escribió:
Thanks for the replies, but it's not what I meant. What I want to be
able to determine is whether or not the user is running from an
interactive shell (like IPython or IDLE). Checking if
__name__=='__main__' checks if the current module is the one being
run, but suppose you have two modules A and B, with the function f
defined in module B that should print 'Interactive' or 'Module' say.
The module A just consists of: import B; B.f(). Now whenever f is
called, __name__ will not be '__main__' for it. Someone using IDLE
could write import B then B.f() too. The question is: is there a way
for f to determine if someone was using an interactive shell to call
it or if it was being called some other way. The way I came up with
works in these limited cases but won't work in a more general
situation (but perhaps there is no way for it to know in the more
general situation).
It depends on what you mean by "an interactive shell"? If you start your
script with:
python -i whatever.py
is it an interactive shell or not?

I tried these two criteria:
a) See if the __main__ module has a __file__ attribute.
b) See if sys.stdin is a real tty

These are the results I got on Windows for several configurations:

<test.py>
import sys
print "__main__ has __file__", hasattr(sys.modules['__main__'], '__file__')
import os
print "sys.stdin is a tty", hasattr(sys.stdin, "fileno") and
os.isatty(sys.stdin.fileno())
</test.py>

python test.py
__main__ has __file__ True
sys.stdin is a tty True

python -i test.py
__main__ has __file__ True
sys.stdin is a tty True

python test.py <nul >nul
__main__ has __file__ True
sys.stdin is a tty True

python test.py <emptyfile >nul
__main__ has __file__ True
sys.stdin is a tty False

pythonw.exe (the consoleless Python executable for Windows)
__main__ has __file__ True
sys.stdin is a tty False

IDLE
__main__ has __file__ False
sys.stdin is a tty False

pythonwin.exe
__main__ has __file__ False
sys.stdin is a tty False
--
Gabriel Genellina

Feb 14 '08 #5
Gabriel Genellina <ga*******@yahoo.com.arwrote:
>a) See if the __main__ module has a __file__ attribute.
b) See if sys.stdin is a real tty
c) See if sys.argv[0] != ''

(Although this works for the command line interactive shell, I've a
suspicion it will fail with IDLE. But I don't have IDLE to hand to
check.)

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Feb 15 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
by: John Lin | last post by:
Howdy, I want to know how to tell if a forked process is done. Actually, my real question is that I want to run a shell script inside of a python script, and after the shell script has...
6
by: Lauren Wilson | last post by:
Hi folks, In an A2K app, I have attempted to use the following command in some VBA code with IDENTICAL results with every single version of the following: Shell "outlook.exe", vbHide Shell...
2
by: Bo Peng | last post by:
Dear list, This may sound strange but I need to start a python shell from python. The motivation is that I have a bunch of (numeric) python functions to provide to a user. The best way I can...
10
by: A.M | last post by:
Hi, I am having difficulty with shell scripting in Python. I use the following command to run a DOS command and put the return value in a Python variable:
5
by: bearophileHUGS | last post by:
For array.array "B" means unsigned char, and such arrays accept to be initialized from (str) strings too, this is quite useful: But it seems such capability isn't shared with the append: ...
3
by: Mark | last post by:
Hello, What I need to know is if there is a better method to run/edit modules on my pc. I'm currently running the IDLE shell under Python 2.5, on Windows XP. Every time I edit my .txt or .py...
3
by: George Sakkis | last post by:
I'm trying to figure out why Popen captures the stderr of a specific command when it runs through the shell but not without it. IOW: cmd = if 1: # this captures both stdout and stderr as...
16
by: pereges | last post by:
Do you see anything wrong about this method ? For eg. I write a shell script a.sh containing : cc -o test file1.c file2.c file3.c and then execute the shell script ( sh a.sh) to compile and...
7
by: Samuel A. Falvo II | last post by:
I have a shell script script.sh that launches a Java process in the background using the &-operator, like so: #!/bin/bash java ... arguments here ... & In my Python code, I want to invoke...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.