【问题标题】:python 2.7 - Inserting input in cmd via subprocess, according to outputpython 2.7 - 根据输出通过子进程在 cmd 中插入输入
【发布时间】:2016-08-11 21:24:48
【问题描述】:

我现在有这个代码

p = subprocess.Popen(args='test.bat'.split(), stdout=sp.PIPE, stdin=sp.PIPE, universal_newlines=True)
p.stdin.write("n")
p.stdin.flush()
for line in p.stdout:
    print line

所以当批处理文件运行时它会询问

Are you sure you want to continue[Y/N]?

你输入n,它再次弹出,接下来n 关闭它。但标准输入只输入第一个n 而不是第二个。如果我只将它与一个n 一起使用,则代码完成并完成,但我如何给子进程 2 个输入?

另一件事:

我想读取输出,这样我就可以运行这样的东西:

p = subprocess.Popen(args='test.bat'.split(), stdout=sp.PIPE, stdin=sp.PIPE, universal_newlines=True)
for line in p.stdout:
     if line.startswith('Please type x/y"):
          p.stdin.write('x')
          p.stdin.flush()
     if line.startswith('please choose 1/2'):
          p.stdin.write('2')
          p.stdin.flush()

现在运行不会进入for,因为子进程没有完成。 第二件事,取第一件事并使其复杂化。所以回答第二个就足够了。 谢谢你

【问题讨论】:

    标签: python-2.7 input subprocess stdin


    【解决方案1】:

    找到了一个答案,希望对其他人有所帮助。

            p = sp.Popen(args='try.bat'.split(), cwd=WORKING_DIRECTORY, shell=True, stdout=sp.PIPE, stdin=sp.PIPE, universal_newlines=True)
            while True:
                nextline = p.stdout.readline()
                if nextline.startswith("enter x/y"):
                    p.stdin.write("y")
                    p.stdin.flush()
                if nextline == '' and p.poll() is not None:
                    break
                sys.stdout.write(nextline)
                sys.stdout.flush()
    

    它将逐行读取,并根据您希望的每一行采取相应的行动

    【讨论】:

      猜你喜欢
      • 2017-08-01
      • 2013-05-12
      • 1970-01-01
      • 2015-04-21
      • 2016-09-30
      • 2013-05-16
      • 2013-12-01
      • 2013-10-08
      相关资源
      最近更新 更多