gpt4 book ai didi

python - 子进程 cmd 返回 null (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:52 25 4
gpt4 key购买 nike

尝试编写一个脚本来检查目录中的文件,然后使用找到的文件名称插入到子进程命令中,如下所示:

for filename in os.listdir('/home/dross/python/scripts/var/running/'):
print(str(filename))
cmd = 'app_query --username=dross --password=/home/dross/dross.txt "select row where label = \'Id: ' + filename + '\' SHOW status"'
print(cmd)
query = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
query.wait()

如果我从命令行手动运行命令,则有 2 个可能返回的值“Error:No result”或“True”

当“错误:无结果”条件为真时,脚本返回相同的结果,但是当“真”条件存在时,不会返回任何内容。如果打印语句的结果被复制并粘贴到操作系统命令行中,它将运行并返回“True”

我在这里看到的欺骗可能是什么?有没有更好的方法来实现我想要做的事情?

最佳答案

您似乎缺少对 .communicate() 的调用,以通过管道读取命令的结果。

在原来的 query = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 中,发送到 stderr 的任何内容都将显示在屏幕上,这似乎就是您的错误消息所发生的情况。发送到 stdout 的任何内容都将发送到管道,准备好使用 communicate()

读取

一些实验表明,除非您与运行的命令进行通信,否则您将看不到写入 subprocess.PIPE channel 的内容,并且 stderr 将如果未重定向,则显示到终端:

>>> import subprocess
>>> query = subprocess.Popen('echo STDERR 1>&2', shell=True, stdout=subprocess.PIPE)
STDERR
>>> query.wait()
0
>>> print(query.communicate())
('', None)

>>> query = subprocess.Popen('echo STDERR 1>&2', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> query.wait()
0
>>> print(query.communicate())
('', 'STDERR\n')

>>> query = subprocess.Popen('echo STDOUT', shell=True, stdout=subprocess.PIPE)
>>> query.wait()
0
>>> print(query.communicate())
('STDOUT\n', None)

因此,要使用问题中的代码,您需要如下所示的代码:

for filename in os.listdir('/home/dross/python/scripts/var/running/'):
print(filename) # print can convert to a string, no need for str()
cmd = 'app_query --username=dross --password=/home/dross/dross.txt "select row where label = \'Id: ' + filename + '\' SHOW status"'
print(cmd)
query = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
query.wait()
output, error = query.communicate()
print("stdout: {}".format(output))
print("stderr: {}".format(error))

关于python - 子进程 cmd 返回 null (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36311044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com