python - 如何在Python中调用程序的 'catch' stdin、stdout、stderr?

标签 python command-line-interface stdout stdin

我有一个sql.exe它有一个命令行界面,接受 sql 查询作为输入并打印结果。我需要用 Python 编写一个程序,它将生成 sql 命令,将它们作为输入传递给该程序并读取输出。

为了练习,我用 python 编写了一个玩具程序,adder.py :

if __name__ == '__main__':
    while True:
        try:
            line = input()
            a, b = line.strip().split()
            c = int(a) + int(b)
            print(c)
        except EOFError:
            exit()
        except:
            continue

我创建了一个in.txt文件:

10 5
7 3
1 a
2 1

我从cmd执行:-$ python adder.py < in.txt > out.txt out.txt 是:

15
10
3

我的问题是,如何流式传输/缓冲输入和输出,以不断与程序通信,而不必一次又一次地创建和读取文件?

最佳答案

在代码中使用 bash 管道和两个不同的函数

尝试用这种方法重新思考你的程序。

./mycode.py -gen | sqlite3 | ./mycode.py -proc
  1. 您的程序将接受一个选择行为的命令行参数
    (生成输入或处理 SQL 的输出)

  2. 字符|是Bash中的管道操作数

  3. 处理 SQL 输出的函数必须读取 stdin

命令行参数

您必须阅读并验证命令行参数并选择执行两个不同的函数。
看到这里How to read/process command line arguments?

Bash 管道

关于 bash 中的管道

command1 | command2

command1 的标准输出通过管道连接到 command2 的标准输入。
示例:echo“我的密码”| shasum -a 256

从标准输入读取

请参阅此处有关如何读取标准输入的一些示例 How do you read from stdin?

示例代码

参见here示例代码。 下面是示例输出(使用 SQLite 在 macOS 和 Ubunto 中测试):

> ./mycode.py -gen
SELECT 0 + 0;
SELECT 1 + 2;
SELECT 2 + 4;
...

> ./mycode.py -gen | sqlite3
0
3
6
...

> # ./mycode.py -proc multiply by 10 the stdin
> ./mycode.py -gen | sqlite3 | ./mycode.py -proc
0
30
60
...

关于python - 如何在Python中调用程序的 'catch' stdin、stdout、stderr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60633398/

相关文章:

python - 将包含整数的数据框列转换为日期

python - 在 Python 中读取目录的安全方法

Linux CLI 查找没有子路径的 dir 路径 - 结果只有父路径

Python 2 和 3 兼容的字符串文件编写器

bash - 在后台 linux 中运行 tcpdump

python - 终止使用 python 子进程 Popen 启动的进程时如何关闭标准输出管道?

python - 为什么 HTTPSConnectionPool 不工作而 PoolManager 工作?

python - pyinstaller 没有名为 pyinstaller 的模块

bash - 有没有办法找到 PATH 设置的位置?

linux - 带有重定向的 linux uniq 命令出错