473,787 Members | 2,932 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

network programming without goto

Please help:

I was really blocked here. without goto I really do
not known how to do it.

The problem is to use PyZ3950 to consult a lists of
hosts and for each of them to search for a list of
targets. Since the network is undetermined, there were
always some exceptions: I would like to allow it to
retry for 3 times. Moreover, during the query process,
the conn will timeout (set by the remote server).
Reconnect is preferred before fail the current search,
but the reconnect may fail even if the first try is
succeed.
for host in hostlist:
try:
# sometimes the host may fail
conn =zoom.Connecton (host.ip, host.port)
except:
continue # Next host? But How to give it some
chance? 3 times?
...
reconnect = 0
for t in targets:
# ?
if reconnect:
# if conn timeout, reconnect
try:
# Fail??? 3 chances rules here?
conn = zoom.Connection (host.ip,
host.port)
except:
# ? Where should I go?
q = buildquery(t)
try: # Hay, any things can be broken
# and after some iteration, conn should
timeout
r = conn.search(q)
except:
reconnect = 1
#??? how to retry this t?

Jul 18 '05 #1
7 1255
In article <ma************ *************** ***********@pyt hon.org>,
kent sin <ke*****@yahoo. com> wrote:
Please help:

I was really blocked here. without goto I really do
not known how to do it.

The problem is to use PyZ3950 to consult a lists of
hosts and for each of them to search for a list of
targets. Since the network is undetermined, there were
always some exceptions: I would like to allow it to
retry for 3 times. Moreover, during the query process,
the conn will timeout (set by the remote server).
Reconnect is preferred before fail the current search,
but the reconnect may fail even if the first try is
succeed.

[spaghetti code deleted for brevity]

The real problem you've got is that you're trying to smash too much
stuff into one function. You've got several things going on here at
once. First, you're iterating over several hosts to try. Next, you're
making several attempts to connect to each host. Lastly, you've got
some buildquery()/search() stuff going on (whatever that may be). I'm
not at all sure what you're trying to do with "for t in targets", but
I'm going to assume it's somehow related to iterating over the various
hosts.

What you want to do is refactor this into a number of smaller functions,
each one encapsulating one piece of the puzzle. To start, I'd build a
function which handled the multiple connection attempts to a given host.
Maybe something like this:

#
# Untested code -- this is just to give you some ideas
# and get you thinking in the right direction
#
def connectWithRetr ies (host, port, retryLimit):
attempts = 0
while attempts < retryLimit:
try:
connection = zoom.Connection (host, port)
return connection
except ConnectionError :
attempts += 1
throw ConnectionError

Then, I'd handle the iteration over multiple hosts:

def connectToSomeHo st (hostlist, port):
for host in hostlist:
try:
connection = connectWithRetr ies (host, port)
return connection
except ConnectionError :
# ignore
throw ConnectionError

Finally, It's time to implement your query logic, which I'll leave as an
exercise for the reader (mostly because I don't really understand what
you're trying to do with that).

None of this is network-specfic or even Python-specific. The idea of
breaking up a complex operation into smaller steps and implementing each
one in its own function is pretty much a universal idea. Each function
can be easily designed and tested on its own (and, later, understood by
a future reader).

The question then becomes, how to decide what stuff to put in what
function? There's no hard and fast rules, but the general idea is that
each function should do one thing, or a small set of very closely
related things. For example, I could imagine possibly combining
connectWithRetr ies() and connectToSomeHo st into a single larger function
that did both tasks, because they're both part of the basic "get a
connection to a host" concept. But, getting the connection and using it
to perform a query definitely don't belong together.

Here's some rules of thumb:

Several smaller functions are usually better than one larger one.

If you can't see the entire function code without scrolling in your
editor, it's too big. With todays windowing systems, that probably
means about 40 lines.

If it's got more than a couple of loops, or more than a couple of try
blocks, you're probably doing too much in a single function.

If you can't explain to somebody in a single sentence what your function
is doing, it's doing too much.

The take-home assignment is to DAGS for "refactorin g". There's been a
lot written on the subject in the last 5-10 years. A lot of what's been
written assumes an object oriented environment (in a C++ or Java like
language), but the basic concepts hold for all languages, and for
procedural as well as OO styles.
Jul 18 '05 #2
On Thu, 25 Nov 2004 06:53:53 -0800 (PST), kent sin <ke*****@yahoo. com>
wrote:

for host in hostlist:
try:
# sometimes the host may fail
conn =zoom.Connecton (host.ip, host.port)
except:
continue # Next host? But How to give it some
chance? 3 times?
...


Roy really posted the definitive answer here, but there is something else
you may find it interesting to try: recursive functions. I played around
with this for a random POV-Ray texture generator I made a while ago
(anyone interested? It's decent :) - nesting levels were somewhat
flexible, and I made the number of nesting levels in different sections
(texture maps, normal maps, etc.) randomised as well.

You do something like

***
def funnyWalk(stuff , NUMBER_OF_THIS_ TRY, NESTING_LEVEL)
if NUMBER_OF_THIS_ TRY > NESTING_LEVEL:
# We're done.
break # Is this valid??? I confuse pascal and python easily :(
NailParrotsFeet ()
if NEED_ANOTHER_CA LL == true:
funnyWalk(stuff ,NUMBER_OF_THIS _TRY+1)

NESTINGLEVEL = 3
funnyWalk(stuff ,1,NESTINGLEVEL )
***

And "NailParrotsFee t()" function will get run 3 times.

Jul 18 '05 #3
Roy Smith wrote:
What you want to do is refactor this into a number of smaller functions,
each one encapsulating one piece of the puzzle. To start, I'd build a
function which handled the multiple connection attempts to a given host.
Maybe something like this:

#
# Untested code -- this is just to give you some ideas
# and get you thinking in the right direction
#
def connectWithRetr ies (host, port, retryLimit):
attempts = 0
while attempts < retryLimit:
try:
connection = zoom.Connection (host, port)
return connection
except ConnectionError :
attempts += 1
throw ConnectionError


IMO, Roy's advice here is spot-on, with one minor technical detail. In
Python, exceptions use 'raise', not 'throw'...

Jeff Shannon
Technician/Programmer
Credit International
Jul 18 '05 #4
In article <10************ *@corp.supernew s.com>,
Jeff Shannon <je**@ccvcorp.c om> wrote:
In Python, exceptions use 'raise', not 'throw'...


Doh! I guess it shows that I've been doing a lot of C++ lately :-)
Jul 18 '05 #5
Roy Smith wrote:
In article <10************ *@corp.supernew s.com>,
Jeff Shannon <je**@ccvcorp.c om> wrote:

In Python, exceptions use 'raise', not 'throw'...

Doh! I guess it shows that I've been doing a lot of C++ lately :-)


Heh. I'm working on a Python test harness that uses a C++ hardware interface
module. I keep writing raise on the C++ side and throw on the Python side.

However, that's nothing compared to the amount of swearing regarding the
uselessness of C++ vectors as compared to Python lists. . .

Cheers,
Nick.
Jul 18 '05 #6
Nick Coghlan schrieb:
Roy Smith wrote:
Jeff Shannon <je**@ccvcorp.c om> wrote:
In Python, exceptions use 'raise', not 'throw'...


Doh! I guess it shows that I've been doing a lot of C++ lately :-)


Heh. I'm working on a Python test harness that uses a C++ hardware
interface module. I keep writing raise on the C++ side and throw on the
Python side.

Isn't "throw something" a much more aggressive act than "raise
something", and might that help? But English isn't my native language so
I may be quite wrong.

--
Dr. Sibylle Koczian
Universitaetsbi bliothek, Abt. Naturwiss.
D-86135 Augsburg

Tel.: (0821) 598-2400, Fax : (0821) 598-2410
e-mail : Si************* @Bibliothek.Uni-Augsburg.DE
Jul 18 '05 #7
On Mon, 29 Nov 2004 16:02:01 +0100, Sibylle Koczian
<Si************ *@Bibliothek.Un i-Augsburg.de> declaimed the following in
comp.lang.pytho n:
Isn't "throw something" a much more aggressive act than "raise
something", and might that help? But English isn't my native language so
I may be quite wrong.
Well... "throw" has the imagery that one it tossing it to a
known target, while "raise" is more "hey, I've got a problem here"...
<G>

So do we

raise cain

or

throw aFit

<G>

-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 18 '05 #8

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

Similar topics

8
50590
by: Alex Ang | last post by:
I have written the following VBScript program. It is stored into a file "map_drive.vbs". It successfully mapped to a network drive \\server1\data. Dim WshNetwork Set WshNetwork = WScript.CreateObject("WScript.Network") sPwd = inputbox("Enter password") WshNetwork.MapNetworkDrive "J:", "\\server1\data", false, "xyz_net\John", sPwd Msgbox "Drives has been map successful"
3
14870
by: Jay | last post by:
Hi, I implemeneted an FTP client and server long time back using Java. I found sockets porgramming in java quite useful and easy to handle. I now wanted to implement a similar program using C++. My questions are 1. How good a language is C++ for network programming? 2. what are good onine resources to learn C++ network programming? 3. How similar it is to Java socket programming? Thanks in advance.
16
660
by: John Baker | last post by:
HI; I feel like a fool..I put CUTE FTP in my last request for help --it should have been CUTE PDF! I have FTP on my mind because I have been working on a web based application, and somehow my brain got stuck on it..sorry! Hi: I need some help writing code that will "print" a report using Cute PDF.
134
8046
by: evolnet.regular | last post by:
I've been utilising C for lots of small and a few medium-sized personal projects over the course of the past decade, and I've realised lately just how little progress it's made since then. I've increasingly been using scripting languages (especially Python and Bourne shell) which offer the same speed and yet are far more simple and safe to use. I can no longer understand why anyone would willingly use C to program anything but the lowest...
20
2949
by: JL | last post by:
I have a need to compute least cost formulations. This seems to be in the domain of "linear programming" of which I know practially nothing. Can anyone in the group give me a point in the right direction...are there any tools/libraries, books, websites, etc. TIA, John
56
5750
by: valentin tihomirov | last post by:
{ int i = 2; } int i = 1; There is no 'i' defined in the 'parent' context from the moment of declaration on. So what is the problem? They tell us they pursue language simplicity. The rule "do not define a variable more than once in the same context" is natural, and simplest therefore. All normal languages obey it therefore. Overcomplicating a grammar by injecting more barrieres is a path
9
2378
by: Mex | last post by:
Hi, I'm looking for a good book for beginners about Network Programming. Besides Stevens' book, I would like something specific for C++ language. Any suggestions? Thanks in advantage, Massimo
1
20646
by: Ryan Liu | last post by:
Hi, I have a 100 clients/ one server application, use ugly one thread pre client approach. And both side user sync I/O. I frequently see the error on server side(client side code is same, but I don't see the error): "System.IO.IOException: Unable to read data from the transport connection:A blocking operation was interrupted by a call to WSACancelBlockingCall"
43
3698
by: Adem24 | last post by:
The World Joint Programming Language Standardization Committe (WJPLSC) hereby proclaims to the people of the world that a new programming language is needed for the benefit of the whole mankind in the 21st millenium. This new language not only differs from existing ones by new features and paradigms but which also brings real advantage by rigourously preventing bad programmer habits by omitting features which are outdated. In the proposed...
0
9655
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4067
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.