Mailing List Archive

Need help with TCP/IP client access from Windows
I need a Windows equivalent of this class for a client I'm writing.

class SessionConnection:
# Encapsulate the line-by-line level of a session with a server.
# This class requires Unix services.
param_names = ('host', 'port', 'username', 'password', 'browse')

def __init__(self, file=".intriguer"):
# Initialize a SessionConnection object from user's stored paramters
self.dotfile = os.path.join(os.environ["HOME"], file)
self.host = "snark.thyrsus.com"
self.port = 99999
self.username = "esr@thyrsus.com"
self.password = "fooup"
self.browse = "netscape -remote 'openURL(%s)'"
try:
dfp = open(self.dotfile);
lexer = shlex.shlex(dfp)
while 1:
variable = lexer.get_token()
if not variable:
break
if not variable in Session.param_names:
raise SyntaxError
if lexer.get_token() != '=':
raise SyntaxError
value = lexer.get_token()
if not value:
raise SyntaxError
setattr(self, variable, value);
dfp.close()
except IOError:
pass # if file is absent, fall back to defaults.
self.socket = None
self.sockfp = None

def __repr__(self):
# Dump current session parameters
res = "# intriguer configuration\n"
for p in Session.param_names:
if getattr(self, p):
res = res + "%s=%s\n" % (p, `getattr(self, p)`)
return res

def wrapup(self):
# Update the dotfile to reflect parameter edits
dfp = open(self.dotfile, "w")
dfp.write(`self`);
dfp.close()

# Establish and break server connections

def connect(self):
# Initialize a server connection.
# Not part of the class initialization sequence only because
# we might want to create an instance just to examine or
# edit the parameters.
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(self.host, self.port)
self.sockfp = self.socket.makefile("r+")

def disconnect(self):
# Terminate a server connection
if self.socket:
self.socket.close()
self.sockfp.close()

# Communication with server

def readline(self):
# Read a raw line from the server
return self.sockfp.readline()

def writeline(self, line):
# Write a raw line to the server
return self.sockfp.write(line + "\n")

# Local service invocations

def browse_url(self, url):
# Point a local browser at a specified URL
os.system(self.browse % url)

The issues here are:

(1) How do I get (at least) line-oriented access to an Internet server
from a Python program running under Windows?

(2) How does one read and write the Windows equivalent of a dotfile?
Must this involve the (shudder) registry?

(3) Is there a reliable way for Python programs under Windows to point a local
browser at a specified URL?
--
<a href="http://www.tuxedo.org/~esr">Eric S. Raymond</a>
Need help with TCP/IP client access from Windows [ In reply to ]
Eric Raymond writes:

> I need a Windows equivalent of this class for a client I'm writing.
[snip]
> The issues here are:
>
> (1) How do I get (at least) line-oriented access to an Internet
> server
> from a Python program running under Windows?

No problem there. (The only difference - when using Python - is that
you can only select on sockets on Windows).

> (2) How does one read and write the Windows equivalent of a dotfile?
> Must this involve the (shudder) registry?

You could, by using Mark's win32 extensions. MS would prefer you
kept this kind of info in the registry, but that doesn't stop
anybody, least of all you <g>.

The issue is really what is meant by a HOME directory. On NT, this
has a certain amount of meaning - there's probably a
%WINDIR%/profiles/%USERNAME% directory tree for that user (where
those funky %...% things are environment vars), but probably it's
safer to get that path out of the registry. On Win9x, it's pretty
meaningless, since a logon and username are pretty much an empty
formality. There's almost no way to keep multiple users on a Win9x
box from stepping on each other. (Of course, I mean multiple serial
users; the only possible kind in Windows).

Probably better just to have a default file, and let the user
override that if need be. Which may well never happen.

> (3) Is there a reliable way for Python programs under Windows to
> point a local
> browser at a specified URL?

The best way is to use WinExec from Mark's win32 extensions. You just
give it the URL and it loads the user's default browser. Using
os.system is harder, because most of the time a browser is not on the
user's path.

However, this worked fine for me:

browse='"C:\\Program Files\\Netscape\\Communicator\\Program\\netscape"
%s'

Note the double quotes around the nowhere-but-Windows <snicker> path
with spaces in it, and that argv[1] is expected to be a URL (same for
IE). Also note that the path doesn't go thru the c runtime lib, so
those wonderful backslashes can't be avoided.

- Gordon
Need help with TCP/IP client access from Windows [ In reply to ]
Hi All--

Gordon "Mr. Spaceman" McMillan wrote:
>
> Eric Raymond writes:
>

[snippet]

> However, this worked fine for me:
>
> browse='"C:\\Program Files\\Netscape\\Communicator\\Program\\netscape"
> %s'
>

Won't work for me--I almost never install NS in the assumed default
path. In fact, the only things I install in the default paths (or even
on the c: drive) are Microsoft goobies, which hate it if you try to
confuse them. Plus I have some systems that have no NetScape on them,
'cause I have to use IE5 for work. Bleaugh.

> Note the double quotes around the nowhere-but-Windows <snicker> path
> with spaces in it, and that argv[1] is expected to be a URL (same for
> IE). Also note that the path doesn't go thru the c runtime lib, so
> those wonderful backslashes can't be avoided.
>

Hey, I got spaces in my directories on Linux! Had'm for years. WFFM!

<there's-always-someone-out-to-puncture-your-balloon>-ly y'rs,
Ivan
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan@callware.com
ivanlan@home.com
http://www.pauahtun.org
See also:
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps: Cu Chi, Class of '70
----------------------------------------------
Need help with TCP/IP client access from Windows [ In reply to ]
About the only way I know to do this at all reliably...

import os
os.system( 'start %s'%url )

Which does whatever the user has defined as the proper thing to do with
urls, normally, launch IE or Netscape.

Hope this helps,
Mike

-----Original Message-----
From: python-list-request@cwi.nl [mailto:python-list-request@cwi.nl]On
Behalf Of Eric S. Raymond
Sent: July 29, 1999 4:33 PM
To: python-list@cwi.nl
Subject: Need help with TCP/IP client access from Windows
...
(3) Is there a reliable way for Python programs under Windows to point a
local
browser at a specified URL?
...
Need help with TCP/IP client access from Windows [ In reply to ]
Gordon McMillan <gmcm@hypernet.com>:
> No problem there. (The only difference - when using Python - is that
> you can only select on sockets on Windows).

So you're saying my blocking-socket code will work as-is? Great. The
Python manual implies otherwise...

> > (2) How does one read and write the Windows equivalent of a dotfile?
> > Must this involve the (shudder) registry?
>
> You could, by using Mark's win32 extensions. MS would prefer you
> kept this kind of info in the registry, but that doesn't stop
> anybody, least of all you <g>.
>
> The issue is really what is meant by a HOME directory. On NT, this
> has a certain amount of meaning - there's probably a
> %WINDIR%/profiles/%USERNAME% directory tree for that user (where
> those funky %...% things are environment vars), but probably it's
> safer to get that path out of the registry. On Win9x, it's pretty
> meaningless, since a logon and username are pretty much an empty
> formality. There's almost no way to keep multiple users on a Win9x
> box from stepping on each other. (Of course, I mean multiple serial
> users; the only possible kind in Windows).

Hm..."serial users". I like that. It just...*sounds right* for Windows.

:-)

> Probably better just to have a default file, and let the user
> override that if need be. Which may well never happen.

OK, but where to put it? I don't know what the conventions are.

> > (3) Is there a reliable way for Python programs under Windows to
> > point a local
> > browser at a specified URL?
>
> The best way is to use WinExec from Mark's win32 extensions. You just
> give it the URL and it loads the user's default browser. Using
> os.system is harder, because most of the time a browser is not on the
> user's path.

Are these in the stock 1.5.2 Windows distribution?

> However, this worked fine for me:
>
> browse='"C:\\Program Files\\Netscape\\Communicator\\Program\\netscape"
> %s'
>
> Note the double quotes around the nowhere-but-Windows <snicker> path
> with spaces in it, and that argv[1] is expected to be a URL (same for
> IE). Also note that the path doesn't go thru the c runtime lib, so
> those wonderful backslashes can't be avoided.

Got it. Thanks.
--
<a href="http://www.tuxedo.org/~esr">Eric S. Raymond</a>

Our society won't be truly free until "None of the Above" is always an option.
Need help with TCP/IP client access from Windows [ In reply to ]
Mike Fletcher <mcfletch@vrtelecom.com>:
> About the only way I know to do this at all reliably...
>
> import os
> os.system( 'start %s'%url )
>
> Which does whatever the user has defined as the proper thing to do with
> urls, normally, launch IE or Netscape.

Really? That sounds perfect. Just for my information, what is `start'?
--
<a href="http://www.tuxedo.org/~esr">Eric S. Raymond</a>

The common argument that crime is caused by poverty is a kind of
slander on the poor.
-- H. L. Mencken
Need help with TCP/IP client access from Windows [ In reply to ]
"Eric S. Raymond" wrote:
>
> Mike Fletcher <mcfletch@vrtelecom.com>:
> > About the only way I know to do this at all reliably...
> >
> > import os
> > os.system( 'start %s'%url )
> >
> > Which does whatever the user has defined as the proper thing to do with
> > urls, normally, launch IE or Netscape.
>
> Really? That sounds perfect. Just for my information, what is `start'?

To a unix person, you could say that it forks into another task,
uses a heuristic to work out how to handle the arguments, and
executes that program. It's a bit bizarre.

The help from NT4WSsp5 is below.

--
/\\\ Mincom | Martin Pool | martinp@mincom.com
// \\\ | Software Engineer | Phone: +61 7 3303-3333
\\ /// | Mincom Ltd. |
\/// | Teneriffe, Brisbane | Speaking for myself only



> help start
Starts a separate window to run a specified program or command.

START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME] [/WAIT] [/B]
[command/program] [param
eters]

"title" Title to display in window title bar.
path Starting directory
I The new environment will be the original environment
passed
to the cmd.exe and not the current environment.
MIN Start window minimized
MAX Start window maximized
SEPARATE Start 16-bit Windows program in separate memory space
SHARED Start 16-bit Windows program in shared memory space
LOW Start application in the IDLE priority class
NORMAL Start application in the NORMAL priority class
HIGH Start application in the HIGH priority class
REALTIME Start application in the REALTIME priority class
WAIT Start application and wait for it to terminate
B Start application without creating a new window. The
application has ^C handling ignored. Unless the
application
enables ^C processing, ^Break is the only way to
interrupt the
application
command/program
If it is an internal cmd command or a batch file then
the command processor is run with the /K switch to
cmd.exe.
This means that the window will remain after the command
has been run.

If it is not an internal cmd command or batch file then
it is a program and will run as either a windowed
application
or a console application.

parameters These are the parameters passed to the command/program


If Command Extensions are enabled, external command invocation
through the command line or the START command changes as follows:

non-executable files may be invoked through their file association just
by typing the name of the file as a command. (e.g. WORD.DOC would
launch the application associated with the .DOC file extension).
See the ASSOC and FTYPE commands for how to create these
associations from within a command script.

When executing an application that is a 32-bit GUI application, CMD.EXE
does not wait for the application to terminate before returning to
the command prompt. This new behavior does NOT occur if executing
within a command script.

When executing a command line whose first token is CMD without an
extension or path qualifier, then replaces CMD with the value of the
COMSPEC variable, thus avoiding picking up random versions of
CMD.EXE when you least expect them.

When executing a command line whose first token does NOT contain an
extension, then CMD.EXE uses the value of the PATHEXT
environment variable to determine which extensions to look for
and in what order. The default value for the PATHEXT variable
is:

.COM;.EXE;.BAT;.CMD

Notice the syntax is the same as the PATH variable, with
semicolons separating the different elements.

When executing a command, if there is no match on any extension, then
looks to see if the name, without any extension, matches a directory
name
and if it does, the START command launches the Explorer on that path.
If done from the command line, it is the equivalent to doing a CD /D
to that path.
Need help with TCP/IP client access from Windows [ In reply to ]
* Mike Fletcher
|
| import os
| os.system( 'start %s'%url )
|
| Which does whatever the user has defined as the proper thing to do with
| urls, normally, launch IE or Netscape.

* Eric S. Raymond
|
| Really? That sounds perfect. Just for my information, what is `start'?

A program that runs another program (according to the help text I got
when I ran it at the command-line prompt with no arguments). However,
on my old Win95 box it doesn't understand about URLs.

--Lars M.
Need help with TCP/IP client access from Windows [ In reply to ]
Eric S. Raymond writes:

> Gordon McMillan <gmcm@hypernet.com>:

> > Probably better just to have a default file, and let the user
> > override that if need be. Which may well never happen.
>
> OK, but where to put it? I don't know what the conventions are.

Probably the same directory where you put your script. (The Win31
convention of putting all ini files in the Windows directory under
<appname>.ini is now, thank goodness, passe).

> > > (3) Is there a reliable way for Python programs under Windows to
> > > point a local
> > > browser at a specified URL?
> >
> > The best way is to use WinExec from Mark's win32 extensions. You just
> > give it the URL and it loads the user's default browser. Using
> > os.system is harder, because most of the time a browser is not on the
> > user's path.
>
> Are these in the stock 1.5.2 Windows distribution?

No, They're in Mark Hammond's extensions (link from python.org). The
"start" trick (which I just tried) is probably the best way in stock
Python (though it raises a bogus console window for a few seconds
before the browser starts).


- Gordon
Need help with TCP/IP client access from Windows [ In reply to ]
In article <19990730005211.T7149@thyrsus.com>,
Eric S. Raymond <esr@thyrsus.com> wrote:
>Gordon McMillan <gmcm@hypernet.com>:
>>
>> Probably better just to have a default file, and let the user
>> override that if need be. Which may well never happen.
>
>OK, but where to put it? I don't know what the conventions are.

I'd stick it in the directory your script is in. That's pretty standard
for Windoze. In fact, I'd make it "<base script name>.ini".
--
--- Aahz (@netcom.com)

Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6 (if you want to know, do some research)
Need help with TCP/IP client access from Windows [ In reply to ]
Gordon McMillan <gmcm@hypernet.com>:
> Probably the same directory where you put your script. (The Win31
> convention of putting all ini files in the Windows directory under
> <appname>.ini is now, thank goodness, passe).

OK. Will giving the filename ".\\intriguer" work for this? And, given
that the filename is going through the C library, will leaving it as
"./intriguer" work?

(Sorry for the newbie questions, but I have zero Windows-programming
experience.)
--
<a href="http://www.tuxedo.org/~esr">Eric S. Raymond</a>

Never trust a man who praises compassion while pointing a gun at you.
Need help with TCP/IP client access from Windows [ In reply to ]
Gordon McMillan <gmcm@hypernet.com>:
> > OK. Will giving the filename ".\\intriguer" work for this? And,
> > given that the filename is going through the C library, will leaving
> > it as "./intriguer" work?
>
> Yes and yes. File Manager doesn't know what to make of an
> extensionless file name, but that's OK. For years I created comma
> delimited files as ".cdf". Then one day I installed IE 4, and they
> magically became "Channel Definition Files".
>
> This is good. It means that while Ionesco is dead, his spirit
> lives on.

:-)

"Six Filenames In Search Of An Editor". (Yes, I know, that's Pirandello.)

I've been considering using .ini format anyway; it's a good match to the
problem domain and the module to parse it is just lying there in 1.5.2.
So I guess I'll go with "./intriguer.ini".

Thanks!
--
<a href="http://www.tuxedo.org/~esr">Eric S. Raymond</a>

"The state calls its own violence `law', but that of the individual `crime'"
-- Max Stirner
Need help with TCP/IP client access from Windows [ In reply to ]
Eric S. Raymond wrote:

> Gordon McMillan <gmcm@hypernet.com>:
> > Probably the same directory where you put your script. (The Win31
> > convention of putting all ini files in the Windows directory under
> > <appname>.ini is now, thank goodness, passe).
>
> OK. Will giving the filename ".\\intriguer" work for this? And,
> given that the filename is going through the C library, will leaving
> it as "./intriguer" work?

Yes and yes. File Manager doesn't know what to make of an
extensionless file name, but that's OK. For years I created comma
delimited files as ".cdf". Then one day I installed IE 4, and they
magically became "Channel Definition Files".

This is good. It means that while Ionesco is dead, his spirit
lives on.

> (Sorry for the newbie questions, but I have zero Windows-programming
> experience.) --

No prob. As long as you don't expect extreme conformance out
of the c runtime lib, you'll do fine.

a-foolish-consistency-etc.-ly y'rs

- Gordon
Need help with TCP/IP client access from Windows [ In reply to ]
In article <7nsf2g$ifp@dfw-ixnews11.ix.netcom.com>,
Aahz Maruch <aahz@netcom.com> wrote:
>In article <19990730005211.T7149@thyrsus.com>,
>Eric S. Raymond <esr@thyrsus.com> wrote:
>>Gordon McMillan <gmcm@hypernet.com>:
>>>
>>> Probably better just to have a default file, and let the user
>>> override that if need be. Which may well never happen.
>>
>>OK, but where to put it? I don't know what the conventions are.
>
>I'd stick it in the directory your script is in. That's pretty standard
>for Windoze. In fact, I'd make it "<base script name>.ini".
>--
> --- Aahz (@netcom.com)
>
>Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
>Hugs and backrubs -- I break Rule 6 (if you want to know, do some research)

Well, that's the "well-behaved" version -- the _really_ standard thing is to
put it in %WINDIR%, to preserve the system's fossil record of every app you
ever ran.

In all seriousness: DON'T write to the registry; DO confine your application
to a single, monlithic directory structure; DON'T worry about multi-user unless
you KNOW the client has a rigidly-enforced set of conventions defining what
"home directory" means.

Best,

Tres.
--
---------------------------------------------------------------
Tres Seaver tseaver@palladion.com 713-523-6582
Palladion Software http://www.palladion.com
Need help with TCP/IP client access from Windows [ In reply to ]
> From: Eric S. Raymond [mailto:esr@thyrsus.com]
>
>
> Gordon McMillan <gmcm@hypernet.com>:
> > > OK. Will giving the filename ".\\intriguer" work for this? And,
> > > given that the filename is going through the C library,
> will leaving
> > > it as "./intriguer" work?
> >

Well, as long as your current working directory is what you want it to be,
sure it'll work, otherwise you'll need to pull the standard "where did I get
run from" nonsense.

Bill
Need help with TCP/IP client access from Windows [ In reply to ]
> From: Bill Tutt
>
> > From: Eric S. Raymond [mailto:esr@thyrsus.com]
> >
> >
> > Gordon McMillan <gmcm@hypernet.com>:
> > > > OK. Will giving the filename ".\\intriguer" work for
> this? And,
> > > > given that the filename is going through the C library,
> > will leaving
> > > > it as "./intriguer" work?
> > >
>
> Well, as long as your current working directory is what you
> want it to be, sure it'll work, otherwise you'll need to pull
> the standard "where did I get run from" nonsense.
>

Something like the following usually does the trick:
import os
import sys

(head, tail) = os.path.split(sys.argv[0])
# If tail is None, then we just got invoked in the current working
directory.
if tail is None:
path = os.getcwd()
else:
# Otherwise, head now contains a possibly relative path to where we were
# invoked from, normalize it.
path = os.sys.abspath(head)
inifile = open('%s/blah.ini' % path, 'r')

Bill
Need help with TCP/IP client access from Windows [ In reply to ]
> -----Original Message-----
> From: Eric S. Raymond [mailto:esr@thyrsus.com]
>
>
> > > (2) How does one read and write the Windows equivalent of
> a dotfile?
> > > Must this involve the (shudder) registry?
> >
> > You could, by using Mark's win32 extensions. MS would prefer you
> > kept this kind of info in the registry, but that doesn't stop
> > anybody, least of all you <g>.
> >
> > The issue is really what is meant by a HOME directory. On NT, this
> > has a certain amount of meaning - there's probably a
> > %WINDIR%/profiles/%USERNAME% directory tree for that user (where
> > those funky %...% things are environment vars), but probably it's
> > safer to get that path out of the registry. On Win9x, it's pretty
> > meaningless, since a logon and username are pretty much an empty
> > formality. There's almost no way to keep multiple users on a Win9x
> > box from stepping on each other. (Of course, I mean multiple serial
> > users; the only possible kind in Windows).
>

Just to be annoying... I thought I'd send out some info on how things are
supposed to work on Win32 boxes.

The correct way to go about doing these things is via the SHGetFolderPath
API.
(Calling SHGetSpecialFolderPath is also ok, but SHGetFolderPath is the
preferred API entry point.)
Docs at:
http://msdn.microsoft.com/library/sdkdoc/shellcc/Shell/Functions/ShGetFolder
Path.htm

A description of all of the special folders is at:
http://msdn.microsoft.com/library/sdkdoc/shellcc/shell/Functions/CSIDL.htm


Ok so can I use these in Python yet?
Unfortunately, not at the moment. If someone screams and yells I'm sure Mark
or I will write the necessary wrapping code.

The preferred place on NT (ignoring terminal server) for per user
application data files to reside in is:
"%WINDIR%\Profiles\%USERNAME%\Application Data\<appname>"
If you don't want the data to roam (assuming your account is setup that
way), the data should go in:
"%WINDIR%\Profiles\%USERNAME%\Local Settings\Application Data\<appname>"

Bill
Need help with TCP/IP client access from Windows [ In reply to ]
Bill Tutt wrote in message
<4D0A23B3F74DD111ACCD00805F31D8100DB90FF7@RED-MSG-50>...

>The correct way to go about doing these things is via the SHGetFolderPath
>API.
>(Calling SHGetSpecialFolderPath is also ok, but SHGetFolderPath is the
>preferred API entry point.)
>Docs at:
>http://msdn.microsoft.com/library/sdkdoc/shellcc/Shell/Functions/ShGetFolde
r
>Path.htm
>
>A description of all of the special folders is at:
>http://msdn.microsoft.com/library/sdkdoc/shellcc/shell/Functions/CSIDL.htm
>
>
>Ok so can I use these in Python yet?
>Unfortunately, not at the moment. If someone screams and yells I'm sure
Mark
>or I will write the necessary wrapping code.

Actually Bill, you can - althought it is well hidden.

There is a win32com.shell.shell extension that covers this. It is part of
the COM extensions as all this cruft is heavily tied to COM - eg, creating
shortcuts, etc etc etc.

>>> from win32com.shell import shell, shellcon
>>> shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_PERSONAL)
L'C:\\WINNT\\Profiles\\skip\\Personal'
>>>

SHGetFolderPath/Location arent exposed - I will add them - but as you
mention, the SHGetSpecial versions do work fine.

Mark.