如何为需要文件名而不是变量的python子进程调用提供输入? [英] How to provide input to a python subprocess call that expects filename, rather than variable?

查看:65
本文介绍了如何为需要文件名而不是变量的python子进程调用提供输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中调用Shell脚本(segment.sh). 在控制台上产生正确结果的语法是:

I'm trying to call a shell script (segment.sh) within python. The syntax that produce correct results at the console is:

> ./segment.sh ctb file.txt utf-8 0

可以看出,该shell脚本期望一个文本文件作为输入.我想做的是打开文件并在python中读取其内容(最好从HTML POST表单中读取),然后以某种方式将包含内容的变量传递给python子进程 打电话.

As can be seen, this shell script expects an text file as input. What I am trying to do is to open up the file and read its content in python (later preferably from an HTML POST form), and somehow pass the variable containing the content to the python subprocess call.

以下功能不起作用.但是,如果我只提供一个文件名,例如:

The following function is not working. But if I just provide a file name such as:

Popen(["/bin/bash", "./segment.sh", "ctb", "file.txt", "utf-8", "0"])`

然后,它将起作用,但是我想从变量传递输入.您能给我一些指点吗?

then, it will work, but I want to pass the input from a variable. Would you please give me some pointers?

def pySegment(text):
    op = subprocess.Popen(["/bin/bash", "./segment.sh", "ctb", "utf-8", "0"],
                      stdout = subprocess.PIPE,
                      stdin  = subprocess.PIPE,
                      stderr = subprocess.STDOUT,                          
                      )
    results = op.communicate(input=text)[0]
    return results

if __name__ == "__main__":
    filename = "./file.txt"
    text = open(filename).read()
    result = pySegment(text)
    print result

推荐答案

我建议使用命名管道:

import os, tempfile, shutil, subprocess

temp_dir = tempfile.mkdtemp()
filename = os.path.join(temp_dir, 'file.txt')
text = '<text>'
os.mkfifo(filename)

try:
    subprocess.Popen(('segment.sh', 'ctf', filename, 'utf-8', '0'))
    with open(filename, 'w') as f:
        f.write(text)
finally:
    shutil.rmtree(temp_dir)

命名管道将提供与文件相同的接口,而无需根据需要真正创建该文件.

The named pipe will offer the same interface of a file without really creating that file as you need.

这篇关于如何为需要文件名而不是变量的python子进程调用提供输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆