写入 Python subprocess.Popen 对象的文件描述符 3 [英] Write to file descriptor 3 of a Python subprocess.Popen object

查看:55
本文介绍了写入 Python subprocess.Popen 对象的文件描述符 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何写入 subprocess.Popen 对象的文件描述符 3?

How do I write to file descriptor 3 of a subprocess.Popen object?

我正在尝试使用 Python 在以下 shell 命令中完成重定向(不使用命名管道):

I'm trying to accomplish the redirection in the following shell command with Python (without using named pipes):

$ gpg --passphrase-fd 3 -c 3<passphrase.txt < filename.txt > filename.gpg

推荐答案

子进程 proc 继承在父进程中打开的文件描述符.因此您可以使用 os.open 打开 passphrase.txt 并获取其关联的文件描述符.然后,您可以构造一个使用该文件描述符的命令:

The subprocess proc inherits file descriptors opened in the parent process. So you can use os.open to open passphrase.txt and obtain its associated file descriptor. You can then construct a command which uses that file descriptor:

import subprocess
import shlex
import os

fd=os.open('passphrase.txt',os.O_RDONLY)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=fd)
with open('filename.txt','r') as stdin_fh:
    with open('filename.gpg','w') as stdout_fh:        
        proc=subprocess.Popen(shlex.split(cmd),
                              stdin=stdin_fh,
                              stdout=stdout_fh)        
        proc.communicate()
os.close(fd)

<小时>

要从管道而不是文件中读取,您可以使用 os.pipe:

import subprocess
import shlex
import os

PASSPHRASE='...'

in_fd,out_fd=os.pipe()
os.write(out_fd,PASSPHRASE)
os.close(out_fd)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=in_fd)
with open('filename.txt','r') as stdin_fh:
    with open('filename.gpg','w') as stdout_fh:        
        proc=subprocess.Popen(shlex.split(cmd),
                              stdin=stdin_fh,
                              stdout=stdout_fh )        
        proc.communicate()
os.close(in_fd)

这篇关于写入 Python subprocess.Popen 对象的文件描述符 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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