473,385 Members | 1,740 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,385 software developers and data experts.

Windows Cmd.exe Window

For my sins I'm a MS Windows user at work and apart from that I have a
small problem ...

I like to write python scripts to do small tasks and then double click
on them from the file explorer to run them.

Unfortunately I'm not perfect and sometimes I make mistakes and have
unhandled exceptions or syntax errors when running the scripts. The
default behaviour is to shut down the command window which leaves you
no chance of reading the exception.

In the past I have created .bat wrapper files that just call the python
interpreter, but it is a bit tedious to have to create a matching .bat
file for every script. So I came up with the following approach...

1. Copy python.exe to pythoncmd.exe
2. Add a bit of stuff to sitecustomize.py
3. Add a special first line to every python script and give it a .cmd
extension.

The stuff added to sitecustomize.py (actually I created a
sitecustomize.py for this) is:
"""
import sys
import os

if os.path.basename(sys.executable) == 'pythoncmd.exe':

def cmdexcepthook(*args):
sys.__excepthook__(*args)
# Let use confirm/inspect error
os.system('pause')

sys.excepthook = cmdexcepthook
"""

The special first line is:

@pythoncmd -x "%~f0" %* & exit /b

(In the python.org FAQ for windows it says
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
but since I have no idea which is "right" I chose the simpler looking
one)

This approach does require pythoncmd.exe to by in your %PATH% but I
think that is reasonable ;)

I am a bit disappointed I couldn't think of a way of deciding if I was
running a ".cmd" file in sitecustomize.py so that I could just use the
normal python.exe. Using a renamed interpreter .exe is just a trick
for detecting when I am running .cmd files, but it means that the
script won't run on another machine that hasn't had the python.exe
copied to pythoncmd.exe on it. Which is a shame.

So my question. Is there a better way? I'm not really happy with this
approach. Should I stop worrying and go and play my new ukulele?
Answers please.

Giles

Jul 21 '05 #1
14 2673
* Giles Brown (2005-07-07 13:56 +0100)
For my sins I'm a MS Windows user at work and apart from that I have a
small problem ...

I like to write python scripts to do small tasks and then double click
on them from the file explorer to run them.

Unfortunately I'm not perfect and sometimes I make mistakes and have
unhandled exceptions or syntax errors when running the scripts. The
default behaviour is to shut down the command window which leaves you
no chance of reading the exception.

In the past I have created .bat wrapper files that just call the python
interpreter, but it is a bit tedious to have to create a matching .bat
file for every script. So I came up with the following approach...

1. Copy python.exe to pythoncmd.exe
2. Add a bit of stuff to sitecustomize.py
3. Add a special first line to every python script and give it a .cmd
extension.

The stuff added to sitecustomize.py (actually I created a
sitecustomize.py for this) is:
"""
import sys
import os

if os.path.basename(sys.executable) == 'pythoncmd.exe':

def cmdexcepthook(*args):
sys.__excepthook__(*args)
# Let use confirm/inspect error
os.system('pause')

sys.excepthook = cmdexcepthook
"""

The special first line is:

@pythoncmd -x "%~f0" %* & exit /b

(In the python.org FAQ for windows it says
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
but since I have no idea which is "right" I chose the simpler looking
one)

This approach does require pythoncmd.exe to by in your %PATH% but I
think that is reasonable ;)

I am a bit disappointed I couldn't think of a way of deciding if I was
running a ".cmd" file in sitecustomize.py so that I could just use the
normal python.exe. Using a renamed interpreter .exe is just a trick
for detecting when I am running .cmd files, but it means that the
script won't run on another machine that hasn't had the python.exe
copied to pythoncmd.exe on it. Which is a shame.

So my question. Is there a better way? I'm not really happy with this
approach. Should I stop worrying and go and play my new ukulele?
Answers please.


I think it's a FAQ to: use raw_input at the end to prevent closing.
Jul 21 '05 #2
Nah. You're missing my point. I only want the command window not to
be closed if there is an *exception*. Picky I know, but there you go.

Giles

Jul 21 '05 #3

On 07.07.2005, at 15:25, Giles Brown wrote:
Nah. You're missing my point. I only want the command window not to
be closed if there is an *exception*. Picky I know, but there you go.


well, then register raw_input as exit function:
import atexit
atexit.register(raw_input)


works fine in my terminal. should do in your framework also.

cheers,

- harold -

--
What is mind? -- Doesn't matter.
What is matter? -- Never mind!
--

Jul 21 '05 #4
Use sys.excepthook to hook a function you define and in that function
print a traceback and pause before exiting. Something like (not tested
but copied from working example):

import sys
def Myexcepthook(type, value, traceback):
print "in Myexcepthook-type=", type," value=",value," traceback=",traceback
import traceback
lines=traceback.format_exception(type, value, traceback)
print "---------------------Traceback lines-----------------------"
print "\n".join(lines)
print "-----------------------------------------------------------"
t=raw_input("Press return to continue")
sys.exit(2)

#
# set sys.excepthook
#
sys.excepthook=Myexcepthook
#
# create an uncaught divide by zero exception
#
a=1/0
-Larry Bates

Giles Brown wrote:
For my sins I'm a MS Windows user at work and apart from that I have a
small problem ...

I like to write python scripts to do small tasks and then double click
on them from the file explorer to run them.

Unfortunately I'm not perfect and sometimes I make mistakes and have
unhandled exceptions or syntax errors when running the scripts. The
default behaviour is to shut down the command window which leaves you
no chance of reading the exception.

In the past I have created .bat wrapper files that just call the python
interpreter, but it is a bit tedious to have to create a matching .bat
file for every script. So I came up with the following approach...

1. Copy python.exe to pythoncmd.exe
2. Add a bit of stuff to sitecustomize.py
3. Add a special first line to every python script and give it a .cmd
extension.

The stuff added to sitecustomize.py (actually I created a
sitecustomize.py for this) is:
"""
import sys
import os

if os.path.basename(sys.executable) == 'pythoncmd.exe':

def cmdexcepthook(*args):
sys.__excepthook__(*args)
# Let use confirm/inspect error
os.system('pause')

sys.excepthook = cmdexcepthook
"""

The special first line is:

@pythoncmd -x "%~f0" %* & exit /b

(In the python.org FAQ for windows it says
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
but since I have no idea which is "right" I chose the simpler looking
one)

This approach does require pythoncmd.exe to by in your %PATH% but I
think that is reasonable ;)

I am a bit disappointed I couldn't think of a way of deciding if I was
running a ".cmd" file in sitecustomize.py so that I could just use the
normal python.exe. Using a renamed interpreter .exe is just a trick
for detecting when I am running .cmd files, but it means that the
script won't run on another machine that hasn't had the python.exe
copied to pythoncmd.exe on it. Which is a shame.

So my question. Is there a better way? I'm not really happy with this
approach. Should I stop worrying and go and play my new ukulele?
Answers please.

Giles

Jul 21 '05 #5

On 07.07.2005, at 15:43, harold fellermann wrote:
On 07.07.2005, at 15:25, Giles Brown wrote:
Nah. You're missing my point. I only want the command window not to
be closed if there is an *exception*. Picky I know, but there you go.


well, then register raw_input as exit function:
import atexit
atexit.register(raw_input)
works fine in my terminal. should do in your framework also.


sorry, I did not think. if you want to wait for input _only_ if
an exception occured, your exit function needs to check for the
exception:
import atexit

def wait_on_exc() : .... import sys
.... if sys.exc_type :
.... raw_input()
.... atexit.register(wait_on_exc)


this should do the job, now.

- harold -
--
What if nothing exists and everything is an illusion?
In this case I definitely overpayed my new carpet!
-- Woody Allen

Jul 21 '05 #6
Thanks for your replies.

I think we might have a miscommunication here as (to my understanding)
neither of your replies actually solve my problem.

After all, the function raw_input is just another way of blocking until
user input. I was already doing that using "os.system('pause')".

To recap, what I'm looking for is a way of setting up specific scripts
(not every script) so that when I double click on it, it runs, but if
there is an exception (even a SyntaxError in the top level script) I
get a traceback in a window that doesn't disappear immediately.

The tricky elements of this are:
1) It can't be done using code in the script itself (such as using an
import statement) because in the presence of a SyntaxError the import
statement is never run. This is why I was looking at sitecustomize.py
2) I don't want to do unusual exception/atexit hooking for every script
and so need to be able to detect when I am running one of these .cmd
type scripts.

I hope this clarifies things. I had hoped that my question was worded
sufficiently well to indicate this wasn't a straight-down-the-line
newbie question (I've been programming in Python for seven years now).
Obviously it wasn't. My apologies.

Giles

Jul 21 '05 #7
"Giles Brown" <gi*********@hotmail.com> writes:
Nah. You're missing my point. I only want the command window not to
be closed if there is an *exception*. Picky I know, but there you go.


I find it useful to set an sys.excepthook which calls the debugger
pdb.pm(). This way I not only see the traceback, but I can also poke
around in the environment to find the problem.

Thomas
Jul 21 '05 #8
Hi Larry,
I mentioned how I am already using "sys.excepthook" in my initial
posting.
What I'm looking for is:
1) Is there any better way of solving the problem than setting
sys.excepthook in sitecustomize.py?
2) Or is there a better way of detecting when I am running a .cmd based
script than the method I proposed?
Hope this clears up what I'm asking for.
Thanks,
Giles

Jul 21 '05 #9
harold fellermann wrote:
sorry, I did not think. if you want to wait for input _only_ if
an exception occured, your exit function needs to check for the
exception:
import atexit

def wait_on_exc() : ... import sys
... if sys.exc_type :
... raw_input()
... atexit.register(wait_on_exc)


this should do the job, now.


Did you think to test your code before posting it?

sys.exc_type is deprecated (you should use sys.exc_info() instead), but
neither will tell you whether the program is exiting as a result of an
exception when called from an atexit function, by the time the atexit
function is called the exception is no longer accessible.

As Larry Bates suggested, the OP needs to use a sys.excepthook.
Unfortunately he doesn't test his code either (the parameter 'traceback'
conflicts with the module 'traceback'), but at least the principle is
correct.

Jul 21 '05 #10
Giles Brown wrote:
The special first line is:

@pythoncmd -x "%~f0" %* & exit /b

(In the python.org FAQ for windows it says
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
but since I have no idea which is "right" I chose the simpler looking
one)

This approach does require pythoncmd.exe to by in your %PATH% but I
think that is reasonable ;)

I am a bit disappointed I couldn't think of a way of deciding if I was
running a ".cmd" file in sitecustomize.py so that I could just use the
normal python.exe. Using a renamed interpreter .exe is just a trick
for detecting when I am running .cmd files, but it means that the
script won't run on another machine that hasn't had the python.exe
copied to pythoncmd.exe on it. Which is a shame.
I'm having problems understanding your problem. If the file is a .cmd
file then surely the second line (i.e. the one immediately following the
python -x command) could simply do "import sethook" where sethook would
be a module that sets your excepthook.

Alternatively you could check at any point whether sys.argv[0] ends with
'.cmd' or '.bat' (after lowercasing).

So my question. Is there a better way? I'm not really happy with
this approach. Should I stop worrying and go and play my new ukulele?
Answers please.


Go on, upload some ukulele playing somewhere.

BTW, another solution is to push the pause command out to the shell:

-----------------------
@setlocal enableextensions & (python -x %~f0 %* || pause) & goto :EOF

import sys
if len(sys.argv) > 1:
sys.exit("this will pause")

-----------------------
will pause only if the python program terminates with a non-zero exit code.
This means messages from sys.exit will cause a pause as well as exceptions.
Jul 21 '05 #11
Hooray! We have a winner!

Thanks Duncan. Your improved shell line will do the job very nicely.
:)

(btw, the problem with "import sethook" at the top of the script is
that syntax errors in the top-level will prevent the import from being
run meaning we don't get our traceback anymore.)

Giles

Jul 21 '05 #12
Addendum - forgot to mention that the problem with checking the
extension of sys.argv[0] is that sys.argv[0] is not set until after
sitecustomize.py is run (and it needs to be in sitecustomize.py not an
imported module due to the top-level SyntaxError problem mentioned in
my other post).

Cheers again for your elegant solution.
Giles

Jul 21 '05 #13

In the past I have created .bat wrapper files that just call the python
interpreter, but it is a bit tedious to have to create a matching .bat
file for every script. So I came up with the following approach...


I frequently use a batch file wrapper. Typically it has a long
friendly name for others in my (non-IT) department, and calls the
actual python script in a subfolder, often with arguments. The last
line of the batch file is usually a pause command.

As an alternative, I have a couple of main procedures wrap a try/except
around the entire script, and if an error occurs, then logs the details
before quitting. I suppose you could also print the error, and add a
call raw_input() so its visible before the window closes.

Hope that helps,
Brian.

Jul 21 '05 #14
Giles, you keep mentioning syntax errors as the (/a) cause of the
problem. I suggest you avoid such problems, so that the import sethook
approach, et al. will actually work. The easiest thing to do is to run
PyChecker on your script prior to executing it. PyChecker will catch
your syntax errors (and a whole host of other things, some of which are
actual problems, some not) and let you know where they are. With that
simple bit of testing, the other approaches that rely on a
syntactically-correct script will work, because you will have corrected
the syntax errors.

You *will* have corrected the syntax errors, right? :)

Jul 21 '05 #15

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

Similar topics

1
by: bill ramsay | last post by:
Dear all. I am using an existing hodge-podge of an application that runs on top of an Access database. This application dials up customer equipment, handshakes then downloads/uploads various...
16
by: Robert Mark Bram | last post by:
Hi All! Is there a way to reference a window by name without doing something like this: open (, 'windowName'); The open method will open a blank window if there is no window with such a name....
1
by: WKC | last post by:
I have a parent window that potentially open a lot of pop windows(let call them children windows) from different page on the parent. Over time, those children windows can add up on the screen if...
0
by: dag | last post by:
Hi! I would like to do an overlap window, over my main window (of my application), with a Progress Bar. Exactly when I push a button of my application I want show a window, with a Progress bar,...
6
by: Ayende Rahien | last post by:
Excetremely annoying problem, I've an application with a long startup time. So I created another form with my logo in it to as a splash screen. The splash screen is run from another thread and is...
14
by: | last post by:
Hi All, I am little confused here, hope you can help me. While processing WM_POWERBROADCAST (wParam=PBT_APMQUERYSUSPEND), I MUST to do some lengthy operation(30 sec) before system Suspends or...
1
by: RJN | last post by:
Hi Sorry for posting again. I open a few pop-up windows from a main window. If session time out occurs in either the main window or the pop-up windows ,I redirect the user to login screen....
3
by: clsmith66 | last post by:
I am building an ASP.NET application where I have been required to make all the editing screens popup windows within the application. I didn't have any trouble creating the new windows but only...
44
by: Viken Karaguesian | last post by:
Hello all, On occasion I want to open hyperlinks (images, etc.) in a new window. In the past, I've used target="_blank" to open the link in a new window. However, using the "target" attribute...
9
by: Reidar | last post by:
Is it possible to have the source in one window and the design in another window and perhaps the code in a third window? reidarT
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.