0
output = cStringIO.StringIO()
output.write('string') # this emulates some_file.txt

p = subprocess.Popen(['perl', 'file.pl'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
line, _ = p.communicate(output.getvalue())
print line
output.close()

This prints Can't open perl script "file.pl": No such file or directory. The python script and perl file are in the same directory!

I want line to be the output of perl file.pl < some_file.txt

How to do this?

jfs
  • 399,953
  • 195
  • 994
  • 1,670
Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130
  • is file.pl in the current working directory? – Chad S. Nov 10 '15 at 17:39
  • @ChadS.Yes, it is in the same directory. I have updated the question. – Animesh Pandey Nov 10 '15 at 17:40
  • Your problem doesn't appear to have anything to do with `subprocess` and `cStringIO`. Try specifying an absolute path to `file.pl`. – martineau Nov 10 '15 at 17:57
  • 2
    _it is in the same directory_ doesn't really answer @ChadS. question about whether its in the current working directory. you could try `os.path.join(os.path.dirname(__file__), 'file.pl')` to explicitly look in the script's directory. – tdelaney Nov 10 '15 at 18:15
  • 2
    Why do you use `shell=True`? I think it is not needed here. If unsure don't use shell=True. – guettli Nov 10 '15 at 18:52
  • related: [Python: StringIO for Popen](http://stackoverflow.com/q/20568107/4279) – jfs Nov 10 '15 at 23:03

1 Answers1

0

I want line to be the output of perl file.pl < some_file.txt

#!/usr/bin/env python
from subprocess import check_output

with open('some_file.txt', 'rb', 0) as file:
    line = check_output(['perl', 'file.pl'], stdin=file)

To fix Can't open perl script "file.pl": No such file or directory, pass the full path to file.pl e.g., if it is in the same directory as your Python script then you could use get_script_dir() function, to get the path.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670