[Tutor] string not found in variable

Alan Gauld alan.gauld at yahoo.co.uk
Sun Mar 21 20:06:21 EDT 2021


On 21/03/2021 22:31, jark AJ wrote:

> 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

Just to be picky, the variable is a name it has no type.
The output that you are storing has a type however.

> 2) Is there a way we could keep appending the output like a list in the
> string. 

A list of strings would seem the most logical option.

> 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.

I'm less clear what you mean here.

> import subprocess
> 
> class Command(object):
>     def __init__(self, cmd):
>         self.cmd = cmd
> 
>     def run(self, shell=False):
>         try:
>             print("Executing Command >>", self.cmd)
>             output = subprocess.Popen(
>                 self.cmd.split(), stdout=subprocess.PIPE, shell=shell
>             )
>             return output.communicate()[0]
>         except subprocess.CalledProcessError as e:
>             return e.returncode

There's an aphorism "When you write a class that only has one
method and an init you should really write a function. This
is compounded when you only create one instance. Its all
a bit of overkill.

>     def __str__(self):
>         return str(self.cmd)

You don't appear to ever call the str() method.

> count = 0
> while count <= 5:

This is probably easier written as

for _ in range(6):

But I suspect from your preamble you really meant

for _ in range(5):

to match your shell example.

>     nc_command = Command("nc -zvw 4 www.google.com 443")
>     output = Command.run(nc_command)

You could probably replace all that with a simple call to the
subprocess module's check_output() function.

>     print(output)
>     print(type(output))
>     print("succeeded!" in output)

> Output:
> __
> 
> ('Executing Command >>', 'nc -zvw 4 www.google.com 443')
> Connection to www.google.com port 443 [tcp/https] succeeded!
> 
> <type 'str'>
> False


I see David has already suggested the output might in fact by
bytes and the docs say:
=======
Captured stdout from the child process. A bytes sequence, or a string if
run() was called with an encoding, errors, or text=True
=========

So it looks like output should be bytes despite what
the type() result says. In that case you need to decode()
the bytes into a string before comparing with a string.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list