如何让Python程序处理here文档?
我编写了一个Python包装器(pyprog)来运行一个程序(someprogram),如下所示:
...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)
用户想要使用shell脚本来运行程序并使用如下所示的此处文档为其提供输入:
#!/bin/sh
pyprog > pyprog.log << EOF
y
file1
file2
EOF
有没有办法生成子进程,以便此处的文档能够工作(“y”被Python input() 消耗,并且“file1”和“file2”继续作为某个程序的标准输入)?现在,Python input() 接受“y”,但其余部分消失了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将
sys.stdin
连接到调用的stdin
。You need to connect
sys.stdin
to thestdin
of the call.我之前已经使用过几次这样的东西: https://gist.github.com/887225
基本上它是一个 python 脚本,它接受许多命令行参数,根据输入的内容执行一些转换,然后使用 os.system() 调用 shell 命令。
在此示例中,我调用 Java,传入类路径,然后运行 ProgramName.jar 程序。
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.