[Tutor] string not found in variable
Cameron Simpson
cs at cskk.id.au
Sun Mar 21 20:11:08 EDT 2021
On 21Mar2021 18:31, jark AJ <jarkmx at gmail.com> wrote:
> There are two actions I am trying to achieve here.
>
>1) To check if the connectivity exists between the source and destination
>2) To run the test five times to ensure there is no intermittent packet
>loss we experience.
>
>looking to use the nc command here in python, On a bash shell, we do it
>using
>for i in {1..5}; do nc -zvw 4 www.google.com 443 ; done
>
>I have the following questions:
>
>1) I am storing the subprocess output in a variable called output which is
>of type string. It has succeeded in the output; however, when I use
>print("succeeded!" in output), its returning false
Well, that means "succeeded!" is not in the output :-)
You'll notice that .communicate() returns (stdout_data,stderr_data). I
would expect that "succeeded!" is in the stderr_data error output.
In the UNIX model, processes by default have an input, an output and an
error output. The separation of the standard output from the rror output
is what lets you write a pipeline like this:
nc .... | grep something-fromthe-server | ...
and still see the error messages - only the standard error output is
directed through the pipe.
Also, the error output is _not_ only for error messages - it is
generally used for "noise", such as progress reporting, which is not to
be mixed in with the commands intended output.
Supposing you'd connected some API and wanted to process maybe some JSON
response. You'd find that 'succeeded!" message polluting the JSON very
troublesome. Such a bug, where informative messages are littering the
data stream is called a Plug in the Taxonimy of Bugs :-)
The other thing I want to recommend is to _not_ rely on finding cheery
strings like "succeeded!" in the output (or error output) as an
indication of success/failure. (I suspect you're not, you're just trying
to debug, but still...)
All programmes should exit with a meaningful exit code, 0 for success,
nonzero for failure. Test that.
Testing the output, particularly the error output is (a) very very
programme specific, whereas the exit code ("returncode" in the
subprocess docs) is reliable and general and (b) very very fragile to
changes in the tool you're testing.
For example, running your nmap command here (MacOS) _does not_ show the
string "succeeded!". Same programme, just a different revision.
>2) Is there a way we could keep appending the output like a list in the
>string. trying to do the success/failure logic at the end based on the
>results of all five tests. Looking to achieve this using the variable which
>stores the output.
Of course. Make a list:
outputs = []
..... communicate ....
outputs.append(error_data)
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list