【问题标题】:Python run multiple prompt commands terminalPython运行多个提示命令终端
【发布时间】:2018-03-04 13:24:51
【问题描述】:

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

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

我尝试使用os.system('./distance vectors_bow.bin & EXIT') 但我得到输出sh: 1: EXIT: not found

当我在终端中手动执行上述过程而不是从 python 脚本中时,它工作正常。怎么做?

【问题讨论】:

  • 尝试以同样的方式运行命令,即distance -> ./distance
  • 抱歉有问题。你现在能告诉我吗

标签: python shell subprocess system


【解决方案1】:

如果我理解正确,您想使用参数 vectors_bow.bin 运行 distance 并获得第一个输入 EXIT

试试这个:

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

编辑: 已修复 python3 需要对输入参数进行编码

【讨论】:

  • 您的问题是正确的,但我收到错误:回溯(最近一次通话最后一次):文件“/home/pawandeep/Desktop/DL_Ass2/wrd2vec_working/test_analogy.py”,第 3 行,在 Popen(['./distance', 'vectors_bow.bin'], stdin=PIPE).communicate('EXIT') 文件 "/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess. py”,第 828 行,在通信 self._stdin_write(input) 文件“/home/pawandeep/anaconda3/envs/untitled/lib/python3.6/subprocess.py”,第 781 行,在 _stdin_write self.stdin.write(input ) TypeError: 需要一个类似字节的对象,而不是 'str'
  • 已修复,我使用的是 python2。但是在python3中字节和字符串不是一回事。
猜你喜欢
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 2018-12-28
  • 2019-12-22
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多