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?

2
  • try to run command in the same way, i.e. distance -> ./distance Commented Mar 4, 2018 at 13:30
  • Sorry for typo in question. Can you tell now Commented Mar 4, 2018 at 13:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 <module> 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'
Fixed, I was using python2. But in python3 bytes and strings are not the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.