Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing a python script to take input from STDIN

Tags:

python

bash

A python script I need to run takes input only from a file passed as a command line argument, like so:

$ markdown.py input_file

Is there any way to get it to accept input from STDIN instead? I want to be able to do this through Bash, without significantly modifying the python script:

$ echo "Some text here" | markdown.py

If I have to modify the Python script, how would I go about it?

(EDIT: Here is the script that is parsing the command line options.)

like image 272
Karthik Avatar asked Jul 17 '10 19:07

Karthik


2 Answers

I'm not sure how portable it is, but on Unix-y systems you can name /dev/stdin as your file:

$ echo -n hi there | wc /dev/stdin
       0       2       8 /dev/stdin
like image 91
Mark Rushakoff Avatar answered Oct 15 '22 05:10

Mark Rushakoff


Make sure this is near the top of the file:

import sys

Then look for something like this:

filename = sys.argv[1]
f = open(filename)

and replace it with this:

f = sys.stdin

It's hard to be more specific without seeing the script that you're starting with.

like image 45
Daniel Stutzbach Avatar answered Oct 15 '22 07:10

Daniel Stutzbach