Python在终端上运行多个提示命令

Python在终端上运行多个提示命令,python,shell,subprocess,system,Python,Shell,Subprocess,System,我想从python脚本运行terminal命令。我知道我可以使用os.system()调用。但这里的问题是,当我运行第一个命令时,我会得到一个提示,其中我必须编写下一个终端命令。例如:- ./distance vectors_bow.bin Enter word or sentence (EXIT to break): EXIT 我尝试使用os.system('./distance vectors\u bow.bin&EXIT') 但是我得到了输出sh:1:EXIT:notfound 当我在

我想从python脚本运行terminal命令。我知道我可以使用
os.system()
调用。但这里的问题是,当我运行第一个命令时,我会得到一个提示,其中我必须编写下一个终端命令。例如:-

./distance vectors_bow.bin 
Enter word or sentence (EXIT to break): EXIT
我尝试使用
os.system('./distance vectors\u bow.bin&EXIT')
但是我得到了输出
sh:1:EXIT:notfound


当我在terminal中手动执行上述过程,但不是从python脚本执行时,它工作得很好。如何操作?

如果我理解正确,您希望使用参数
vectors\u bow.bin运行
distance
,并进行第一次输入
退出

试试这个:

from subprocess import Popen, PIPE
Popen(['distance', 'vectors_bow.bin'], stdin=PIPE).communicate('EXIT'.encode())
编辑:
修复了python3需要对输入参数进行编码的问题,如果我理解正确,您希望使用参数
vectors\u bow.bin运行
距离
,并进行第一次输入
退出

试试这个:

from subprocess import Popen, PIPE
Popen(['distance', 'vectors_bow.bin'], stdin=PIPE).communicate('EXIT'.encode())
编辑:
修复了python3需要对输入参数进行编码的问题

请尝试以相同的方式运行命令,即
distance
->->
/distance
很抱歉出现问题。你能告诉我现在试着用同样的方式运行命令吗,即
distance
->
/distance
对不起,这里有问题。你现在能告诉我你的问题是正确的,但我得到了错误:回溯(最近一次调用最后一次):文件“/home/pawandeep/Desktop/DL_Ass2/wrd2vec_working/test\u simulation.py”,第3行,Popen(['./distance',vectors\u bow.bin'],stdin=PIPE)。通信('EXIT')文件“/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py”,第828行,在communicate self.\u stdin_write(input)File“/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py”中,\u stdin_write self.stdin.write(input)TypeError:像object这样的字节是必需的,而不是'str'修复的,我使用的是python2。但是在python3中,字节和字符串不是一回事。你答对了问题,但我得到了错误:回溯(最近一次调用):文件“/home/pawandeep/Desktop/DL_Ass2/wrd2vec_working/test_simulation.py”,第3行,在Popen(['./distance',vectors\u bow.bin',stdin PIPE)中。通信('EXIT')文件“/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py”,在通信self.\u stdin\u write(输入)文件中的第828行“/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py”,在写入self.stdin.write(输入)中的第781行TypeError:bytes-like对象是必需的,而不是'str'修复的,我使用的是python2。但是在python3中,字节和字符串不是一回事。