0

I want to run terminal command from python script. I know I can use os.system() call. But problem here is when I run first command I get a prompt in which I have to write next terminal command. For example:-

./distance vectors_bow.bin 
Enter word or sentence (EXIT to break): EXIT

I tried to use os.system('./distance vectors_bow.bin & EXIT') but I get output sh: 1: EXIT: not found.

It works fine when I do the above process manually in terminal but not from python script. How to do it?

Pawandeep Singh
  • 830
  • 1
  • 13
  • 25

1 Answers1

2

If I understand correctly you want to run distance with parameter vectors_bow.bin and have the first input EXIT

try this:

from subprocess import Popen, PIPE
Popen(['distance', 'vectors_bow.bin'], stdin=PIPE).communicate('EXIT'.encode())

EDIT: Fixed for python3 needed encode for the input parameter

Eran
  • 2,324
  • 3
  • 22
  • 27
  • You got the question correct but I am getting error : Traceback (most recent call last): File "/home/pawandeep/Desktop/DL_Ass2/wrd2vec_working/test_analogy.py", line 3, in Popen(['./distance', 'vectors_bow.bin'], stdin=PIPE).communicate('EXIT') File "/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py", line 828, in communicate self._stdin_write(input) File "/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py", line 781, in _stdin_write self.stdin.write(input) TypeError: a bytes-like object is required, not 'str' – Pawandeep Singh Mar 04 '18 at 13:38
  • Fixed, I was using python2. But in python3 bytes and strings are not the same thing. – Eran Mar 04 '18 at 14:00