【问题标题】:python3 woes with passing string to stdin of subprocesspython3 将字符串传递给子进程的标准输入时遇到问题
【发布时间】:2019-05-07 04:55:22
【问题描述】:

如何使这个 unix 命令...在 python3 中工作?

unix 命令

echo 'alter table in db' | zenity --text-info --width 600 --height 300 --title 'has this sql been done?'

上面的命令会弹出一个带有文本的框,然后我可以捕获用户的响应。

在 python3 中,我认为我可以将其写入子进程的标准输入,但我不断收到无法解决的神秘错误

下面是执行此操作的python程序

#!/usr/bin/env python3
import subprocess

cmd = ['zenity', '--text-info', '--width', 600, '--height', 300, '--title', 'has this sql been done?']

pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,  stderr=subprocess.STDOUT)

data='alter table in db'

resp = pipe.communicate(input=data)[0]

这个 python 脚本失败了

Traceback (most recent call last):
    pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE,  stderr=subprocess.STDOUT)
  File "/usr/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.6/subprocess.py", line 1275, in _execute_child
    restore_signals, start_new_session, preexec_fn)
TypeError: expected str, bytes or os.PathLike object, not int

我们将不胜感激任何想法

【问题讨论】:

  • 你的第一个 cmd 列表包含整数; 600和300。我想这是你的第一个问题。

标签: python python-3.x subprocess pipe


【解决方案1】:

这个:

cmd = ['zenity', '--text-info', '--width', 600, '--height', 300, '--title', 'has this sql been done?']

应该是这样的:

cmd = ['zenity', '--text-info', '--width', '600', '--height', '300', '--title', 'has this sql been done?']

即使 300 和 600 是数字,您仍然可以在命令行中将它们显示为字符串。

【讨论】:

  • 感谢阿德里安,我遇到了两个问题。该命令需要像您所说的那样在 INT 周围加上引号,但我也不能只将文本发送到管道的输入,它必须转换为字节数组(例如 bytearray('plain text', 'utf -8') 而不是仅在 unix shell 中工作的“纯文本”)
  • 我相信您使用的是 Python 3。在 Python 中,您有字符串,它是 unicode(没有任何特定编码)。但是,当您将字符串发送到其他地方(例如保存到文件)时,您必须给它一个编码。因此,您必须先将其转换为字节字符串是正确的(但对我来说,我只会做"string".encode("utf-8"))。如果您更喜欢隐含:在Popen() 中,传入universal_newlines=True
【解决方案2】:

!/usr/bin/env python3

导入子流程

cmd = ['zenity', '--text-info', '--width', '600', '--height', '300', '--title', '这个sql做完了吗?']

pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)

data='改变数据库中的表'

resp = pipe.communicate(input=bytearray(data, 'utf-8'))[0]

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 2018-12-09
    • 2011-07-07
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    相关资源
    最近更新 更多