Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IPython: how do I pipe something into a Python script

I understand I can run a script in IPython via run test.py and debug from there.

But how do I pipe an output into test.py? For example, normally I could run in the command line like grep "ABC" input.txt | ./test.py, but how do I do the same thing in IPython?

Thanks!

like image 889
CuriousMind Avatar asked May 19 '12 02:05

CuriousMind


People also ask

How do I import IPython into Python?

Create a folder called startup if it's not already there. Add a new Python file called start.py. Put your favorite imports in this file. Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!

How do I load files into IPython?

A text file can be loaded in a notebook cell with the magic command %load . the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

What is %% Writefile in Jupyter Notebook?

%%writefile lets you output code developed in a Notebook to a Python module. The sys library connects a Python program to the system it is running on. The list sys. argv contains the command-line arguments that a program was run with.


1 Answers

Inside the Python script you should be reading from sys.stdin:

import sys

INPUT = sys.stdin

def do_something_with_data(line):
    # Do your magic here
    ...
    return result

def main():
    for line in INPUT:
        print 'Result:', do_something_with_data(line)

if __name__ == '__main__':
    main()

Inside the iterative interpreter you can use the subprocess module mock sys.stdin.

In[0]: from test.py import *
In[1]: INPUT = subprocess.Popen(['grep', 'ABC', 'input.txt'], \
                               stdout=subprocess.PIPE).stdout
In[2]: main()

You can also pipe the output to a file and just read from the file. For practical purposes stdin is just another file.

In[0]: ! grep "ABC" input.txt > output.txt
In[1]: INPUT = open('output.txt')
In[2]: main()
like image 160
Paulo Scardine Avatar answered Nov 15 '22 16:11

Paulo Scardine