Setting win32 console title from Python

R

runes

Hi,
I'm trying to set the title of the console window (CMD.EXE) in Windows.
I want it set to the basename of the current directory and it should
stay after the script has finished.

Now, the console title is easily set with the DOS-command 'title
NewTitle'. But I'd like to do this from a Python script.

os.system('title NewTitle') will not do, because it spawns a new
process.

win32api.SetConsoleTitle('NewTitle') will not do either, because the
NewTitle is reset as soon as the script finishes.

Chris Gonnerman's WConio
<http://newcenturycomputers.net/projects/wconio.html>
has a settitle() method and
WConio.settitle("NewTitle") does what I want, but not under CMD.EXE,
only COMMAND.EXE.

Any ideas?
 
D

Duncan Booth

runes said:
I'm trying to set the title of the console window (CMD.EXE) in Windows.
I want it set to the basename of the current directory and it should
stay after the script has finished.

Any ideas?
I don't think you can do that.

Whenever you start an application from the command prompt the title is
modified by appending a dash and the name of the program you started. When
the application terminates the title is reset (to remove the name of the
running program). So any change to the title will only last until the next
time CMD.EXE prompts for input. The exception is that any title set using
the TITLE command becomes the reset title for that command prompt.

I can think of only one way round this, which is to run your python program
from a batch file and find some way to pass the desired title back to the
batch file where you can set it with the TITLE command. For example, you
could write the title to a temporary file, or if your program doesn't
produce much other output print it to stdout and parse the program output
using a for command:

e.g. This sets the title to the current time:

C:\>FOR /F "tokens=*" %i in (
More? 'python -c "from time import *; print asctime(localtime())"'
More? ) DO @TITLE %i

C:\>

Obvious notes: In a batch file you would double the % characters, and you
don't type C:\> or More? as these are the prompts from CMD.EXE. Also this
won't work on really old versions of CMD.EXE or with COMMAND.COM.
 
J

jay graves

Hmm.
From an interactive interpreter this works for me.

import os
os.system('title Jay')

but the title returns to its previous value when I Ctrl-Z out of the
process.

If I save this as a file and run it, it seems to work without spawning
a new window but resets it the title after the program finishes like
above.

import os
os.system('title Jay')
x = raw_input()

You mention that the SetConsoleTitle api resets itself after the script
finishes so I'm assuming that 'title' command is just calling the same
api under the covers.

What is your requirement specifically? I do something similar but in a
different way but it might not be what you are after.

I have a 'projects' directory where I keep all of my work. I have
written a small python script 'p.py' that I call like this

p [s|e|*] projectname

the 's' is for shell
the 'e' is for explorer window
the '*' is for both shell and explorer

If there is only one argument, I assume it is the project name and I
default the other argument to 'e'.

if the projectname doesn't have any wildcard characters, I append a '*'
and glob my project directory with that value. if the glob call only
returns a single value, I go ahead and do what was requested (open a
shell or explorer window to that directory) if there is more than one
value returned, I present a numbered menu of project directories that
match and wait for input on which one to open.

The point to all this, is that when I open a shell from p.py I use this
command.
os.system(r'start "%s" /D%s\%s' % (proj,directory,proj))

This spawns a new cmd window with the title of my project name.
Spawning the process with the correct name from the beginning seems to
do the trick.
But like I said, I don't really know your exact requirements.

HTH.
....
jay
 
R

runes

Whenever you start an application from the command prompt the title
is
modified by appending a dash and the name of the program you started. When
the application terminates the title is reset (to remove the name of the
running program). So any change to the title will only last until the next
time CMD.EXE prompts for input. The exception is that any title set using
the TITLE command becomes the reset title for that command prompt.

Thanks Duncan! That sounds reasonable. What I do today is actually
using a .BAT file and read the name from a temp file created by a
python script. It works, but it's slow and the "batchfile-language"
gives me the creep ;-)

I'll try to find out why it does work in command.exe/WConio though.
 
R

runes

Hi Jay. It seems like my requirement is a light edition of your. I like
having many console windows open, and to make it easier to switch
between them, I like to name them. Todays solution is rather tedious

- a batch file that calls a python script that isolates the directory
name and stores it in temp file the batch file reads and use as
argument in the title command.

It works fine, but I dislike the combination and the entire concept of
having to create a temporary file for such a small task. The "batch
language" is probably the most terrible scripting environment ever
created ;-)
 
J

jay graves

Cool. Let me know if you want a copy of p.py (in all of it's
hard-coded glory).
I can easily put it under Public Domain and you can copy whatever you
want out of it.
....
jay
 
D

Duncan Booth

runes said:
Hi Jay. It seems like my requirement is a light edition of your. I like
having many console windows open, and to make it easier to switch
between them, I like to name them. Todays solution is rather tedious

- a batch file that calls a python script that isolates the directory
name and stores it in temp file the batch file reads and use as
argument in the title command.

It works fine, but I dislike the combination and the entire concept of
having to create a temporary file for such a small task. The "batch
language" is probably the most terrible scripting environment ever
created ;-)

As I showed in my other post you can parse program output without using a
temporary file.

If all you want to do is to run a script which sets the title when CMD.exe
starts, that is actually quite easy:

---- c:\temp\startcmd.py ----
import os
print "Python startup"
os.execv('c:\\windows\\system32\\cmd.exe',
["/D", "/C", "title", "CMD - " + os.getcwd()]
-----------------------------

Then run regedit and find the key
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun

edit it and insert the name of your script (in this example
c:\temp\startcmd.py).

Now whenever you start a new command processor the script will set the
title and CMD will NOT reset it. It seems that if you set the title from a
subprocess when CMD is starting it will accept your change.

Warning: don't use os.system from the startcmd.py script as that would run
CMD.exe without the /D flag which would run the script recursively as it
starts.
 
R

runes

Hi Duncan, sorry, I was unprecise. I'm thinking of a script, called
t.py that can be used in the console like an ordinary command. Som if
I change directory from S:\scripts to d:\projects and execute the
script the title changes to "projects" etc.

I have that functionality today with a combination of a python script
and a batch file. I just wondered if I could use python all the way.
Apparently I cannot.

Here are the scripts:


------ DirInPath:\t.bat --------------------------------
@echo off
:: reads bare directory name from file
:: created by external Python script
set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp
PyBareDir.py %DIR_FILE_NAME%

for /F "eol=;" %%t in (%DIR_FILE_NAME%) do (
title %%t
)

del /Q /F DOS_IS_TERRIBLE.tmp
------------------------------------------------------------


------ DirInPath:\PyBareDir.py --------------------------------
# extracts bare directory name and writes
# it to file with name given as argument.

from os import getcwd
from os.path import basename
import sys

try:
saveAsName = sys.argv[1]
lastDir = basename(getcwd())
XWwz(saveAsName, 'w+').write(lastDir + '\n;')
except:
print "PyBareDir failed:", sys.exc_info()[1]

-----------------------------------------------------------------------
 
B

Bengt Richter

Hi Duncan, sorry, I was unprecise. I'm thinking of a script, called
t.py that can be used in the console like an ordinary command. Som if
I change directory from S:\scripts to d:\projects and execute the
script the title changes to "projects" etc.

I have that functionality today with a combination of a python script
and a batch file. I just wondered if I could use python all the way.
Apparently I cannot.

Here are the scripts:


------ DirInPath:\t.bat --------------------------------
@echo off
:: reads bare directory name from file
:: created by external Python script
set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp
PyBareDir.py %DIR_FILE_NAME%

for /F "eol=;" %%t in (%DIR_FILE_NAME%) do (
title %%t
)

del /Q /F DOS_IS_TERRIBLE.tmp
------------------------------------------------------------


------ DirInPath:\PyBareDir.py --------------------------------
# extracts bare directory name and writes
# it to file with name given as argument.

from os import getcwd
from os.path import basename
import sys

try:
saveAsName = sys.argv[1]
lastDir = basename(getcwd())
XWwz(saveAsName, 'w+').write(lastDir + '\n;')
except:
print "PyBareDir failed:", sys.exc_info()[1]

I think I'd try one of the win32 api packages and see if SetConsoleTitle
would work. I.e., from some old API docs:
----
The SetConsoleTitle function sets the title bar string for the current console window.

BOOL SetConsoleTitle(

LPTSTR lpszTitle // address of new title
);
Parameters

lpszTitle

Points to a null-terminated string that contains the string to appear in the title bar of the console window.

Return Value

If the function succeeds, the return value is TRUE.
If the function fails, the return value is FALSE. To get extended error information, call GetLastError.

See Also

GetConsoleTitle
----

Alternatively, you could compile your own extension for
title setting/getting called consoletitle.dll
using the above API (assuming it works) and
its companion GetConsoleTitle.

Regards,
Bengt Richter
 
D

Duncan Booth

runes said:
Hi Duncan, sorry, I was unprecise. I'm thinking of a script, called
t.py that can be used in the console like an ordinary command. Som if
I change directory from S:\scripts to d:\projects and execute the
script the title changes to "projects" etc.

I have that functionality today with a combination of a python script
and a batch file. I just wondered if I could use python all the way.
Apparently I cannot.
I think not, although you probably can do it with only the batch file. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top