How do I pipe output from one python script as input to another python script?

后端 未结 3 386
[愿得一人]
[愿得一人] 2021-01-25 05:59

For example:

A script1.py gets an infix expression from the user and converts it to a postfix expression and returns it or prints it to stdout

script2.py gets a

3条回答
  •  走了就别回头了
    2021-01-25 06:45

    For completion's sake, and to offer an alternative to using the os module:

    The fileinput module takes care of piping for you, and from running a simple test I believe it'll make it an easy implementation.

    To enable your files to support piped input, simply do this:

    import fileinput
    with fileinput.input() as f_input:  # This gets the piped data for you
        for line in f_input:
            # do stuff with line of piped data
    

    all you'd have to do then is:

    $ some_textfile.txt | ./myscript.py
    

    Note that fileinput also enables data input for your scripts like so: $ ./myscript.py some_textfile.txt $ ./myscript.py < some_textfile.txt

    This works with python's print output just as easily:

    >test.py  # This prints the contents of some_textfile.txt
    with open('some_textfile.txt', 'r') as f:
        for line in f:
            print(line)
    
    $ ./test.py | ./myscript.py
    

    Of course, don't forget the hashbang #!/usr/bin/env python at the top of your scripts for this way to work.

    The recipe is featured in Beazley & Jones's Python Cookbook - I wholeheartedly recommend it.

提交回复
热议问题