Python Forum

Full Version: Unix Utilities: yes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
http://man7.org/linux/man-pages/man1/yes.1.html

https://en.wikipedia.org/wiki/Yes_(Unix) Wrote:yes is a Unix command, which outputs an affirmative response, or a user-defined string of text continuously until killed.

In C (from Wikipedia):
#include <stdio.h>

int main(int argc, char *argv[]) {
  if (argc == 1) {
    while (1) {
      printf("y\n");
    }
  } else {
    while (1) {
      for (int i = 1; i < argc; i++){
        printf("%s ",argv[i]);
      }
      printf("\n");
    }
  }
}
In Python:
import sys

def spew_words(words):
   phrase = " ".join(words)
   while True:
       print(phrase)

if __name__ == "__main__":
   args = sys.argv[1:]
   if not args:
       args = ["y"]

   try:
       spew_words(args)
   except KeyboardInterrupt as err:
       # this is the expected way to stop the program
       # ...aside from broken pipes
       pass
Usage:
Output:
E:\Projects\etc> python yes.py y y y y #etc E:\Projects\etc> python yes.py spam eggs spam eggs spam eggs spam eggs spam eggs spam eggs spam eggs spam eggs #etc
As an aside, I think taking common code/utilities and showing how they can be done in python is a cool project.