DEV Community

Nivethan
Nivethan

Posted on

A Mail Command in Python - 03 Standard Input

Welcome back! At this point we have our command line flags all ready to go. The next thing we need is to be able either pipe in input from stdin or enter it in manually. Both of these things are the same thankfully.

Python has an input function that we can use like:

anything = input()
print(anything)
Enter fullscreen mode Exit fullscreen mode

This will take in one line of text. However we want to feed in any number of lines into our program. To do this, we can read from stdin from python through the sys module.

#!/usr/bin/env python3
import argparse
import sys

def main():
    ...
    args = parser.parse_args()

    body = []
    for line in sys.stdin:
        body.append(line)
    body = "".join(body)

    print(args)
    print(body)
Enter fullscreen mode Exit fullscreen mode

Here we will loop through the standard input until a ctrl D. The ctrl D is a character that will trigger a flush of the input and will let our program continue.

We read each line into an array and then join it together. You should notice that we delimit our array with a null string, this is because the new line characters will be part of input already, so don't need to add it in manually.

Now we can do the following:

> ./pymail -s "A body" -c test@example.com -c another@example.com -r nivethant@example.com -t another_to@example.com nivethan@test.com
Hi!
Namespace(attachment=[], cc_address=['test@example.com', 'another@example.com'], from_address='nivethant@example.com', html_flag=False, subject='A body', to_address=['another_to@example.com', 'nivethan@test.com'])
Hi!
Enter fullscreen mode Exit fullscreen mode

This let's us supply a body where we run out python mail application. We use the ctrl D to finish our input.

We can also run our program by piping in the body:

> echo "Hi!" | ./pymail -s "A body" -c test@example.com -c another@example.com -r nivethant@example.com -t another_to@ex
ample.com nivethan@test.com
Namespace(attachment=[], cc_address=['test@example.com', 'another@example.com'], from_address='nivethant@example.com', html_flag=False, subject='A body', to_address=['another_to@example.com', 'nivethan@test.com'])
Hi!
Enter fullscreen mode Exit fullscreen mode

Voila! We can now have an e-mail body. The next step is to write our mail function. Once we do that we can glue our main function which is our command processor and our mail function which handles the actual mailing of things.

Onwards!

Top comments (0)