pythonstdin_如何在Python中执行将数据写入stdin的进程?

我的

Python脚本中有一个标志,指定我是否设置和使用外部进程.此过程是一个名为my_command的命令,它从标准输入中获取数据.如果我在命令行上运行它,它将是这样的:

$my_command < data > result

我想使用Python脚本通过修改标准输入并将其提供给my_command来生成数据行.

我正在做这样的事情:

import getopt, sys, os, stat, subprocess

# for argument's sake, let's say this is set to True for now

# in real life, I use getopt.getopt() to decide whether this is True or False

useProcess = True

if useProcess:

process = subprocess.Popen(['my_command'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

for line in sys.stdin:

# parse line from standard input and modify it

# we store the result in a variable called modified_line

modified_line = line + "foo"

# if we want to feed modified_line to my_command, do the following:

if useProcess:

process.stdin.write(modified_line)

# otherwise, we just print the modifie

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值