开发者

How to make a Python program handle a here document?

开发者 https://www.devze.com 2023-02-20 00:31 出处:网络
I\'ve written a Python wrapper (pyprog) to run a program (someprogram), something like this: ...do some setup stuff in Python...

I've written a Python wrapper (pyprog) to run a program (someprogram), something like this:

...do some setup stuff in Python...
print("run [y=yes]")
CHOICE=input()
...do some setup stuff in Python...
if CHOICE == "y":
  status=subprocess.call(["someprogram"开发者_运维知识库])
  sys.exit(status)

A user wants to use a shell script to run the program and feed it input using a here document like this:

#!/bin/sh
pyprog > pyprog.log << EOF
y
file1
file2
EOF

Is there a way to spawn the subprocess so that the here document will work (the "y" gets consumed by the Python input(), and the "file1" and "file2" continue along as stdin to someprogram)? Right now, the Python input() takes the "y", but the rest of it disappears.


You need to connect sys.stdin to the stdin of the call.

status=subprocess.call(["someprogram"], stdin=sys.stdin)


import sys
status=subprocess.call(["someprogram"], stdin=sys.stdin)


I've used something like this a few times before: https://gist.github.com/887225

Basically it's a python script that accepts a number of command line parameters, performs some transformation based on what was input, then uses os.system() to evoke a shell command. In this example I'm calling Java, passing in a class path then running the ProgramName.jar program.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号