Rocksolid Light

Welcome to RetroBBS

mail  files  register  newsreader  groups  login

Message-ID:  

"Life sucks, but it's better than the alternative." -- Peter da Silva


devel / comp.lang.python / Re: Do subprocess.PIPE and subprocess.STDOUT sametime

SubjectAuthor
* Do subprocess.PIPE and subprocess.STDOUT sametimeHorst Koiner
+* Re: Do subprocess.PIPE and subprocess.STDOUT sametimeMats Wichmann
|`* Re: Do subprocess.PIPE and subprocess.STDOUT sametimeHorst Koiner
| `- Re: Do subprocess.PIPE and subprocess.STDOUT sametimeChris Angelico
+- Re: Do subprocess.PIPE and subprocess.STDOUT sametimeThomas Passin
+- Re: Do subprocess.PIPE and subprocess.STDOUT sametimejak
+- Re: Do subprocess.PIPE and subprocess.STDOUT sametimeEryk Sun
+- Re: Do subprocess.PIPE and subprocess.STDOUT sametimeDieter Maurer
`- Re: Do subprocess.PIPE and subprocess.STDOUT sametimeMats Wichmann

1
Do subprocess.PIPE and subprocess.STDOUT sametime

<40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27598&group=comp.lang.python#27598

  copy link   Newsgroups: comp.lang.python
X-Received: by 2002:ac8:7f8f:0:b0:3ef:3126:7dca with SMTP id z15-20020ac87f8f000000b003ef31267dcamr5901729qtj.2.1683655988968;
Tue, 09 May 2023 11:13:08 -0700 (PDT)
X-Received: by 2002:a05:6870:1010:b0:193:fa9e:873e with SMTP id
16-20020a056870101000b00193fa9e873emr5769923oai.11.1683655988773; Tue, 09 May
2023 11:13:08 -0700 (PDT)
Path: i2pn2.org!i2pn.org!weretis.net!feeder6.news.weretis.net!panix!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!peer03.iad!feed-me.highwinds-media.com!news.highwinds-media.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.python
Date: Tue, 9 May 2023 11:13:08 -0700 (PDT)
Injection-Info: google-groups.googlegroups.com; posting-host=141.70.45.4; posting-account=BgXR-goAAABfh3D4rpbvVjOLIidKMlrh
NNTP-Posting-Host: 141.70.45.4
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
Subject: Do subprocess.PIPE and subprocess.STDOUT sametime
From: koinerhorst6@gmail.com (Horst Koiner)
Injection-Date: Tue, 09 May 2023 18:13:08 +0000
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
X-Received-Bytes: 3127
 by: Horst Koiner - Tue, 9 May 2023 18:13 UTC

Hi @all,
i'm running a program which is still in development with subprocess.run (Python version 3.10), further i need to capture the output of the program in a python variable. The program itself runs about 2 minutes, but it can also freeze in case of new bugs.

For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.

What I tried until now:
1. Poll the the output and use Popen instead:

# Start the subprocess
process = subprocess.Popen(['./test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

captured_output = b''
process_running = True
while process_running:
process_running = (process.poll() is not None)
for pipe in [ process.stdout, process.stderr ]:
while line := pipe.readline():
print(line)
captured_output += line

print(captured_output)
return_code = process.returncode

=> But this is discouraged by the python doc, since it says that polling this way is prone to deadlocks. Instead it proposes the use of the communicate() function.

2. Use communicate() with timeout.
=> This works not at all since when the timeout occurs an exception is thrown and communicate returns at all.

3. Use threading instead
=> For being that simple and universal like subprocess you will more or less reimplement subprocess with threading, like its done in subprocess.py. Just for a debug output the effort is much to high.

#######################################################
Do you have further ideas for implementing such a behavior?
Do you think that a feature request should be done of I'm omitting something obvious?

Thanks you in advance for your suggestions,
Horst.

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.39.1683659154.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27599&group=comp.lang.python#27599

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!newsreader4.netcologne.de!news.netcologne.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: mats@wichmann.us (Mats Wichmann)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Tue, 9 May 2023 13:05:39 -0600
Lines: 53
Message-ID: <mailman.39.1683659154.13552.python-list@python.org>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<9da63d82-55d2-bb0c-33d2-10b5d28a8dc8@wichmann.us>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de rbdEwl4jxA4Pj1S1apQ/IgjUwtFu/xZI60SB9Mvb1zig==
Return-Path: <mats@wichmann.us>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="1024-bit key; unprotected key"
header.d=pobox.com header.i=@pobox.com header.b=Fi69YL4P;
dkim-adsp=none (unprotected policy); dkim-atps=neutral
X-Spam-Status: OK 0.010
X-Spam-Evidence: '*H*': 0.98; '*S*': 0.00; 'debug': 0.07; '(python':
0.09; 'console,': 0.09; 'freeze': 0.09; 'timeout': 0.09;
'received:173': 0.13; 'afterwards': 0.16; 'bugs.': 0.16;
'captured': 0.16; 'fetch': 0.16; 'for.': 0.16; 'none)': 0.16;
'pipe': 0.16; 'run,': 0.16; 'stdout': 0.16; 'threading': 0.16;
'timeout.': 0.16; 'variable.': 0.16; 'wrote:': 0.16; 'python':
0.16; 'says': 0.17; 'instead': 0.17; 'to:addr:python-list': 0.20;
'communicate': 0.22; 'exception': 0.22; 'returns': 0.22;
'version': 0.23; 'run': 0.23; 'tried': 0.26; 'done': 0.28;
'output': 0.28; 'header:User-Agent:1': 0.30; 'program': 0.31;
'think': 0.32; "doesn't": 0.32; 'minutes,': 0.32; 'but': 0.32;
"i'm": 0.33; 'there': 0.33; 'same': 0.34; 'mean': 0.34; 'header
:In-Reply-To:1': 0.34; 'running': 0.34; 'runs': 0.35;
'understood': 0.35; 'received:192.168': 0.37; 'way': 0.38;
'quite': 0.39; 'use': 0.39; 'still': 0.40; 'place.': 0.40;
'something': 0.40; 'want': 0.40; 'should': 0.40; 'true': 0.63;
'send': 0.63; 'universal': 0.64; 'less': 0.65; 'further': 0.69;
'subject:skip:s 10': 0.69; 'production': 0.71; 'deal': 0.73;
'capture': 0.84; 'catch': 0.84; 'discouraged': 0.84; 'poll': 0.84;
'polling': 0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed; d=pobox.com; h=message-id
:date:mime-version:subject:to:references:from:in-reply-to
:content-type:content-transfer-encoding; s=sasl; bh=Dp6D8OE263UE
sVyTIKxmT9Vw7ydmuALfuGvk+A5gOe0=; b=Fi69YL4Pmu0VLdUwxhY4VrLNvrle
zovRiZbJrf0qBzAnHC6gzZEDPEVQrkzDDfMCV68MGDpE7oAvS0jBNmYTd/mAVavl
qRolrbb+5ZroHN7INx1kL8V0NJoOUH6Hr2K55ushp9YuMjtXIUrFxf9QJH/5Kwig
xYpsIL1eauh2GIs=
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed; d=wichmann.us;
h=message-id:date:mime-version:subject:to:references:from:in-reply-to:content-type:content-transfer-encoding;
s=2018-07.pbsmtp; bh=Dp6D8OE263UEsVyTIKxmT9Vw7ydmuALfuGvk+A5gOe0=;
b=AlK5Ab2SqeqQsUBwoU02Jb7iPiDlWn1rMTeREg6jLkggv4OzAYtlukdyLNlpn32nanaqDYc7r2fnq3hOuNvvOVBj8dEAMAEM+3uhN+/aN3yxqmcA+v+SqVbIOnM7K1dZZqEcdS33r5h4BHqa5YH4Lkk7AuqMyVic9F7DXPiIVMo=
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101
Thunderbird/102.10.0
Content-Language: en-US
In-Reply-To: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
X-Pobox-Relay-ID: 7DDEED36-EE9C-11ED-BA9B-C2DA088D43B2-81526775!pb-smtp20.pobox.com
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <9da63d82-55d2-bb0c-33d2-10b5d28a8dc8@wichmann.us>
X-Mailman-Original-References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
 by: Mats Wichmann - Tue, 9 May 2023 19:05 UTC

On 5/9/23 12:13, Horst Koiner wrote:
> Hi @all,
> i'm running a program which is still in development with subprocess.run (Python version 3.10), further i need to capture the output of the program in a python variable. The program itself runs about 2 minutes, but it can also freeze in case of new bugs.
>
> For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.

I'm not sure you quite understood what subprocess.STDOUT is for. If you
say nothing stdout is not captured. STDOUT is used as a value for stderr
to mean send it the same place as stdout, which is useful if you set
stdout to something unusual, then you don't have to retype it if you
want stderr going the same place. The subprocess module, afaik, doesn't
even have a case for stdout=STDOUT.

>
> What I tried until now:
> 1. Poll the the output and use Popen instead:
>
> # Start the subprocess
> process = subprocess.Popen(['./test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>
> captured_output = b''
> process_running = True
> while process_running:
> process_running = (process.poll() is not None)
> for pipe in [ process.stdout, process.stderr ]:
> while line := pipe.readline():
> print(line)
> captured_output += line
>
> print(captured_output)
> return_code = process.returncode
>
> => But this is discouraged by the python doc, since it says that polling this way is prone to deadlocks. Instead it proposes the use of the communicate() function.
>
> 2. Use communicate() with timeout.
> => This works not at all since when the timeout occurs an exception is thrown and communicate returns at all.

Well, sure ... if you set timeout, then you need to be prepared to catch
the TimeoutExpired exception and deal with it. That should be entirely
normal.

>
> 3. Use threading instead
> => For being that simple and universal like subprocess you will more or less reimplement subprocess with threading, like its done in subprocess.py. Just for a debug output the effort is much to high.

Not sure I get what this is asking/suggesting. If you don't want to
wait for the subprocess to run, you can use async - that's been fully
implemented.

https://docs.python.org/3/library/asyncio-subprocess.html

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.40.1683662102.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27602&group=comp.lang.python#27602

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!lilly.ping.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: list1@tompassin.net (Thomas Passin)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Tue, 9 May 2023 15:39:19 -0400
Lines: 50
Message-ID: <mailman.40.1683662102.13552.python-list@python.org>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<f9735819-11f6-fc44-8b04-80fde8108d02@tompassin.net>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de nzfZoObobUYTdqp1wWHQvAXqhqa4wnsakg4O+KNOYh9Q==
Return-Path: <list1@tompassin.net>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=tompassin.net header.i=@tompassin.net header.b=GwW02PeX;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.003
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'thread': 0.05; 'debug':
0.07; '(python': 0.09; 'console,': 0.09; 'filled': 0.09; 'freeze':
0.09; 'received:23.83.212': 0.09;
'received:elm.relay.mailchannels.net': 0.09; 'situation,': 0.09;
'timeout': 0.09; 'afterwards': 0.16; 'bugs.': 0.16; 'captured':
0.16; 'fetch': 0.16; 'none)': 0.16; 'pipe': 0.16;
'received:10.0.0': 0.16; 'received:64.90': 0.16;
'received:64.90.62': 0.16; 'received:64.90.62.162': 0.16;
'received:dreamhost.com': 0.16; 'solved': 0.16; 'stdout': 0.16;
'thread.': 0.16; 'threading': 0.16; 'timeout.': 0.16; 'variable.':
0.16; 'wrote:': 0.16; 'python': 0.16; 'says': 0.17; 'instead':
0.17; "aren't": 0.19; 'pm,': 0.19; 'to:addr:python-list': 0.20;
'communicate': 0.22; 'exception': 0.22; 'returns': 0.22;
'version': 0.23; 'run': 0.23; 'tried': 0.26; 'done': 0.28;
'output': 0.28; 'ideas': 0.28; 'header:User-Agent:1': 0.30;
'program': 0.31; 'think': 0.32; "doesn't": 0.32; 'minutes,': 0.32;
'received:10.0': 0.32; 'received:mailchannels.net': 0.32;
'received:relay.mailchannels.net': 0.32; 'but': 0.32; "i'm": 0.33;
'there': 0.33; 'header:In-Reply-To:1': 0.34; 'running': 0.34;
'runs': 0.35; 'request': 0.35; 'main': 0.37; 'way': 0.38; 'read':
0.38; 'least': 0.39; 'use': 0.39; 'block': 0.39; 'still': 0.40;
'data.': 0.40; 'program.': 0.40; 'something': 0.40; 'should':
0.40; 'true': 0.63; 'send': 0.63; 'universal': 0.64; 'your': 0.64;
'less': 0.65; 'let': 0.66; 'back': 0.67; 'header:Received:6':
0.67; 'received:64': 0.67; 'exactly': 0.68; 'further': 0.69;
'subject:skip:s 10': 0.69; 'production': 0.71; 'capacity': 0.76;
'quickly': 0.80; 'up,': 0.84; 'capture': 0.84; 'discouraged':
0.84; 'lose': 0.84; 'poll': 0.84; 'polling': 0.84
X-Sender-Id: dreamhost|x-authsender|tpassin@tompassin.net
ARC-Seal: i=1; s=arc-2022; d=mailchannels.net; t=1683661160; a=rsa-sha256;
cv=none;
b=Zt8BilL/hxzwzIx4oti8ql6lXPUN3UD8a5BJyYPh7svlBLJE3vcJXuDoAQigXDm71Fk7vr
vK/T1L9XFbCBt1un98OgTWRi2riKU/p4kx+uDdgBFe3yD8c5d+kZ8EketITQeX7pda7kjU
Uoh6349NF1XTJMJE7ZFRymb1DHZYACuN2glGCh8IYZiHpMV104VSxmHgsgkjR3cuOxowQk
wMmMtG9cjzXZv7qAzZm4VSmAel4s+IssRl61pkUBb3ynm4Vv3gYzKrZ9eqp3Hh3fQ+ef93
JF0xAIzGV8ejRY0TgXwripC3Kgl0SMeO1YFdQtn5BSDdq5CKBbhG00H7L/gsmg==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed;
d=mailchannels.net; s=arc-2022; t=1683661160;
h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
to:to:cc:mime-version:mime-version:content-type:content-type:
content-transfer-encoding:content-transfer-encoding:
in-reply-to:in-reply-to:references:references:dkim-signature;
bh=C9cxEE+Xh6XEtDpis6hY6lUn0X0ZoAwJrV6BGZPVnCM=;
b=kzjluNBRrA8BmRB5Zi/c6+L2f5BEbBPVQExPwJ/8X68VUXY0pJ5Ty4lXQaegSl1x3S7Y1s
MIjopQPCRA1wuxE2xzFlq3ErTRbfllCqeJPfcugZJCeqR63dHxfZN/wHr6hxcgV3F5OEch
x6inD8TWqWBa45PZor/mz2eYEs/LvHsE+jHTv26bO+tG/qbDw4V+bea7H/UxnIAx7P9BKI
QUL1oN86ZvqrZHkgk2+P8I/l0TGweYcQtbMFFxdJeaxd5kb+WWsjuWCSqwqzpwu0PxacyZ
xFc5ipJYMlM+/5ezWrdATH3qNqbmtLO+aZej6KwAtvRgLbuTvfI3nJKS1qulgQ==
ARC-Authentication-Results: i=1; rspamd-79bb5575d7-sgx77;
auth=pass smtp.auth=dreamhost smtp.mailfrom=list1@tompassin.net
X-Sender-Id: dreamhost|x-authsender|tpassin@tompassin.net
X-MC-Relay: Neutral
X-MailChannels-SenderId: dreamhost|x-authsender|tpassin@tompassin.net
X-MailChannels-Auth-Id: dreamhost
X-Language-Inform: 45e40b4c46943193_1683661160935_2098807181
X-MC-Loop-Signature: 1683661160935:2416734253
X-MC-Ingress-Time: 1683661160934
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=tompassin.net;
s=dreamhost; t=1683661160;
bh=C9cxEE+Xh6XEtDpis6hY6lUn0X0ZoAwJrV6BGZPVnCM=;
h=Date:Subject:To:From:Content-Type:Content-Transfer-Encoding;
b=GwW02PeXM5tWiZskxIaDdqdJlLCWvlCH5nTVDbTseENR26Ft9l8Y2QRwClbjVMImq
JiLStQIG5tPU9dmNirYDpcyeZ3m+oHcXzqX/nvnBpu3nF7bDSpZsyiRpciarpCSDy8
YWqdc1A1hE/8Xq1QDCTZQ8DpmXGEHIYDTTsEHi0BcJ6JqPC/N89QMnf/8tOGzKaHQ0
kH2/YzugowQ5Bgg8RRA2+BGfE/mdKVOXvCmkei8GXYzRb1CAeudKUOI75lWmfb95Rq
ktdP9JvyvfYoPwePaekcmKOFjvdOOggY+cdhRStUAvjbvwITWPlIAoa6Tt7QW4Wh4/
ZsZXzZuV95amg==
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101
Thunderbird/102.10.1
Content-Language: en-US
In-Reply-To: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <f9735819-11f6-fc44-8b04-80fde8108d02@tompassin.net>
X-Mailman-Original-References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
 by: Thomas Passin - Tue, 9 May 2023 19:39 UTC

On 5/9/2023 2:13 PM, Horst Koiner wrote:
> Hi @all,
> i'm running a program which is still in development with subprocess.run (Python version 3.10), further i need to capture the output of the program in a python variable. The program itself runs about 2 minutes, but it can also freeze in case of new bugs.
>
> For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.
>
> What I tried until now:
> 1. Poll the the output and use Popen instead:
>
> # Start the subprocess
> process = subprocess.Popen(['./test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>
> captured_output = b''
> process_running = True
> while process_running:
> process_running = (process.poll() is not None)
> for pipe in [ process.stdout, process.stderr ]:
> while line := pipe.readline():
> print(line)
> captured_output += line
>
> print(captured_output)
> return_code = process.returncode
>
> => But this is discouraged by the python doc, since it says that polling this way is prone to deadlocks. Instead it proposes the use of the communicate() function.
>
> 2. Use communicate() with timeout.
> => This works not at all since when the timeout occurs an exception is thrown and communicate returns at all.
>
> 3. Use threading instead
> => For being that simple and universal like subprocess you will more or less reimplement subprocess with threading, like its done in subprocess.py. Just for a debug output the effort is much to high.
>
> #######################################################
> Do you have further ideas for implementing such a behavior?
> Do you think that a feature request should be done of I'm omitting something obvious?

I'm not sure if this exactly fits your situation, but if you use
subprocess with pipes, you can often get a deadlock because the stdout
(or stderr, I suppose) pipe has a small capacity and fills up quickly
(at least on Windows), then it blocks until it is emptied by a read.
But if you aren't polling, you don't know there is something to read so
the pipe never gets emptied. And if you don't read it before the pipe
has filled up, you may lose data.

I solved that by running communicate() on a separate thread. Let the
communicate block the thread until the process has completed, then have
the thread send the result back to the main program. Of course, this
won't work if your process doesn't end since you won't get results until
the process ends.

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<u3ediq$cm79$1@dont-email.me>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27605&group=comp.lang.python#27605

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: nospam@please.ty (jak)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Tue, 9 May 2023 23:22:34 +0200
Organization: A noiseless patient Spider
Lines: 47
Message-ID: <u3ediq$cm79$1@dont-email.me>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Injection-Date: Tue, 9 May 2023 21:22:35 -0000 (UTC)
Injection-Info: dont-email.me; posting-host="3791f98456821a6db65e870354c99d8a";
logging-data="415977"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18FlpX+8SaM38VvJxjp2i9V"
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101
Firefox/91.0 SeaMonkey/2.53.16
Cancel-Lock: sha1:BXr6zFNKLFeZTQzKjIyVZbGSQKw=
In-Reply-To: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
 by: jak - Tue, 9 May 2023 21:22 UTC

Horst Koiner ha scritto:
> Hi @all,
> i'm running a program which is still in development with subprocess.run (Python version 3.10), further i need to capture the output of the program in a python variable. The program itself runs about 2 minutes, but it can also freeze in case of new bugs.
>
> For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.
>
> What I tried until now:
> 1. Poll the the output and use Popen instead:
>
> # Start the subprocess
> process = subprocess.Popen(['./test.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>
> captured_output = b''
> process_running = True
> while process_running:
> process_running = (process.poll() is not None)
> for pipe in [ process.stdout, process.stderr ]:
> while line := pipe.readline():
> print(line)
> captured_output += line
>
> print(captured_output)
> return_code = process.returncode
>
> => But this is discouraged by the python doc, since it says that polling this way is prone to deadlocks. Instead it proposes the use of the communicate() function.
>
> 2. Use communicate() with timeout.
> => This works not at all since when the timeout occurs an exception is thrown and communicate returns at all.
>
> 3. Use threading instead
> => For being that simple and universal like subprocess you will more or less reimplement subprocess with threading, like its done in subprocess.py. Just for a debug output the effort is much to high.
>
> #######################################################
> Do you have further ideas for implementing such a behavior?
> Do you think that a feature request should be done of I'm omitting something obvious?
>
> Thanks you in advance for your suggestions,
> Horst.
>

I agree with @'thomas Passin' but I solved in a different way, I made
the Readline() not blocking. even if I believe his idea better than
mine:

os.set_blocking(process.stdout.fileno(), False)
os.set_blocking(process.stderr.fileno(), False)

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.42.1683674237.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27608&group=comp.lang.python#27608

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: eryksun@gmail.com (Eryk Sun)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Tue, 9 May 2023 18:17:13 -0500
Lines: 64
Message-ID: <mailman.42.1683674237.13552.python-list@python.org>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<f9735819-11f6-fc44-8b04-80fde8108d02@tompassin.net>
<CACL+1au2yaCcanLq9MAcnFrudtwKVQyCH1paVypyHsutqMBe0A@mail.gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
X-Trace: news.uni-berlin.de FGJi+dRsF/0MII6V5m2g8wEMR+WxTbckTTh3+jrD11lQ==
Return-Path: <eryksun@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=gldhG3Lg;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.005
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; '(e.g.': 0.05; 'thread':
0.05; 'windows,': 0.05; 'loop': 0.07; 'parent': 0.07;
'allocation': 0.09; 'asynchronous': 0.09; 'blocking': 0.09;
'cases.': 0.09; 'cc:addr:python-list': 0.09; 'child': 0.09;
'filled': 0.09; 'situation,': 0.09; 'skip:_ 20': 0.09; 'threads':
0.09; 'timeout': 0.09; 'cc:no real name:2**0': 0.14; '"import':
0.16; "'python": 0.16; 'accessed': 0.16; 'completion': 0.16;
'empty,': 0.16; 'naive': 0.16; 'pipe': 0.16; 'process).': 0.16;
'relatively': 0.16; 'rounded': 0.16; 'size)': 0.16; 'stdout':
0.16; 'timeout.': 0.16; 'windows.': 0.16; 'wrote:': 0.16; 'uses':
0.19; "aren't": 0.19; 'bug': 0.19; 'calls': 0.19; 'implement':
0.19; 'cc:addr:python.org': 0.20; 'written': 0.22; 'cc:2**0':
0.25; '>>>': 0.28; 'example,': 0.28; 'default': 0.31; 'specified':
0.32; 'message-id:@mail.gmail.com': 0.32; 'skip:2 10': 0.32;
'but': 0.32; "i'm": 0.33; 'there': 0.33; 'particular': 0.33;
'windows': 0.34; 'same': 0.34; 'header:In-Reply-To:1': 0.34;
'received:google.com': 0.34; 'meaning': 0.35; 'following': 0.35;
'from:addr:gmail.com': 0.35; 'processes': 0.36; 'using': 0.37;
'received:209.85': 0.37; 'could': 0.38; 'read': 0.38;
'received:209': 0.39; 'two': 0.39; 'least': 0.39; 'enough': 0.39;
'handle': 0.39; 'use': 0.39; 'block': 0.39; 'still': 0.40;
'data.': 0.40; 'seconds': 0.40; 'something': 0.40; 'should': 0.40;
'potential': 0.60; "there's": 0.61; 'mode': 0.62; 'true': 0.63;
'range': 0.64; 'your': 0.64; 'named': 0.65; 'exactly': 0.68;
'order': 0.69; 'subject:skip:s 10': 0.69; 'within': 0.69;
'ignore': 0.71; 'process,': 0.75; 'read,': 0.75; 'capacity': 0.76;
'handles': 0.76; 'implemented': 0.76; 'quickly': 0.80;
'practical': 0.84; 'up,': 0.84; 'honor': 0.84; 'hr,': 0.84;
'lose': 0.84; 'pipes': 0.84; 'polling': 0.84; 'polls': 0.84;
'received:209.85.161': 0.84; 'side.': 0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20221208; t=1683674234; x=1686266234;
h=cc:to:subject:message-id:date:from:references:in-reply-to
:mime-version:from:to:cc:subject:date:message-id:reply-to;
bh=xUBB+LiAVQJLMuhWaWaFYWXpZIun2N39R8u5sESjleM=;
b=gldhG3Lgolws8vtreHjrxsFkMnotf/iszkvwDr3BBZTre48ajtRyEXV9QIHRkkq5iQ
dGJgDXzWEbhOhtaTt8/L947nMckI1PBzsw3YABfu1Qj+vjIYNqd9EHvF5YIjIQVPfDmZ
FiSvgOpCpKCIsiXxtBYS5ABpo+sVtYm59DEQxIAI3HWR8e6024r5clu5X+5cQGBIfk4W
k9t4TgpQW1msM5/VvCl58bt4Mvbl/1Gm5jONi6s+2kRZYBMuJ2FIIyQv9NSCaw4EBybF
p6kREvWFKXPLTiaju9LQcpUkiQsV2qWEKbgjB+GZdIHCDDy6QKk54hC7s19H3e0PUSZm
2wtw==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20221208; t=1683674234; x=1686266234;
h=cc:to:subject:message-id:date:from:references:in-reply-to
:mime-version:x-gm-message-state:from:to:cc:subject:date:message-id
:reply-to;
bh=xUBB+LiAVQJLMuhWaWaFYWXpZIun2N39R8u5sESjleM=;
b=F0qdi1ic5Jg7eGrA9sz0QWpvU87p2tmEMSelMOJ+Oviii0LTlx9dRP7rt+XrwPtRpj
k86s3PbW5Xid71weDmh7mb61CEXM49d9Pw1DL3Pp3iWHNCPOVXDEZcDX5iiBmV3Fstl8
TK8NHdRaY1QOosVN2ck7mIOmiNS0sepJXukxUoaTTFZvxY9J21H4eAffuBAvcB8/m2hQ
tBradxOIoo2Y0ysAB1iNhnYjzyDbO27148kdV9zQI8xAh3CDnRb3dRU+AcBE2LjrMRpA
BisuhWy6wYQxU5FzaW6hHhzNKSHxgmhA+QhQte4/IU1m1SL+v8YJOdLwsy402LG0OeVV
bPXQ==
X-Gm-Message-State: AC+VfDzzSkbR+FdhXHaH0m/gB+OUD7Pe4+gI61ApTE7j3MpuN6iMA+9j
8txK25SCHGpY829Dvkp6zO6vaAolDCF9Ugx1om/YQijg
X-Google-Smtp-Source: ACHHUZ4UTur/9hD0pKgQkgRBwmebD/uq5UMzrrzDibRntPtQCbWF9c/nToXFWP7upi+tTH0zO3Hj4Jyxl8QNEs1b00A=
X-Received: by 2002:a05:6808:65a:b0:38d:edd7:8cd4 with SMTP id
z26-20020a056808065a00b0038dedd78cd4mr2033089oih.53.1683674234134; Tue, 09
May 2023 16:17:14 -0700 (PDT)
In-Reply-To: <f9735819-11f6-fc44-8b04-80fde8108d02@tompassin.net>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <CACL+1au2yaCcanLq9MAcnFrudtwKVQyCH1paVypyHsutqMBe0A@mail.gmail.com>
X-Mailman-Original-References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<f9735819-11f6-fc44-8b04-80fde8108d02@tompassin.net>
 by: Eryk Sun - Tue, 9 May 2023 23:17 UTC

On 5/9/23, Thomas Passin <list1@tompassin.net> wrote:
>
> I'm not sure if this exactly fits your situation, but if you use
> subprocess with pipes, you can often get a deadlock because the stdout
> (or stderr, I suppose) pipe has a small capacity and fills up quickly
> (at least on Windows),

The pipe size is relatively small on Windows only because
subprocess.Popen uses the default pipe size when it calls WinAPI
CreatePipe(). The default size is 4 KiB, which actually should be big
enough for most cases. If some other pipe size is passed, the value is
"advisory", meaning that it has to be within the allowed range (but
there's no practical limit on the size) and that it gets rounded up to
an allocation boundary (e.g. a multiple of the system's virtual-memory
page size). For example, here's a 256 MiB pipe:

>>> hr, hw = _winapi.CreatePipe(None, 256*1024*1024)
>>> _winapi.WriteFile(hw, b'a' * (256*1024*1024))
(268435456, 0)
>>> data = _winapi.ReadFile(hr, 256*1024*1024)[0]
>>> len(data) == 256*1024*1024
True

> then it blocks until it is emptied by a read.
> But if you aren't polling, you don't know there is something to read so
> the pipe never gets emptied. And if you don't read it before the pipe
> has filled up, you may lose data.

If there's just one pipe, then there's no potential for deadlock, and
no potential to lose data. If there's a timeout, however, then
communicate() still has to use I/O polling or a thread to avoid
blocking indefinitely in order to honor the timeout.

Note that there's a bug in subprocess on Windows. Popen._communicate()
should create a new thread for each pipe. However, it actually calls
stdin.write() on the current thread, which could block and ignore the
specified timeout. For example, in the following case the timeout of 5
seconds is ignored:

>>> cmd = 'python -c "import time; time.sleep(20)"'
>>> t0 = time.time(); p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
>>> r = p.communicate(b'a'*4097, timeout=5); t1 = time.time() - t0
>>> t1
20.2162926197052

There's a potential for deadlock when two or more pipes are accessed
synchronously by two threads (e.g. one thread in each process). For
example, reading from one of the pipes blocks one of the threads
because the pipe is empty, while at the same time writing to the other
pipe blocks the other thread because the pipe is full. However, there
will be no deadlock if at least one of the threads always polls the
pipes to ensure that they're ready (i.e. data is available to be read,
or at least PIPE_BUF bytes can be written without blocking), which is
how communicate() is implemented on POSIX. Alternatively, one of the
processes can use a separate thread for each pipe, which is how
communicate() is implemented on Windows.

Note that there are problems with the naive implementation of the
reader threads on Windows, in particular if a pipe handle leaks to
descendants of the child process, which prevents the pipe from
closing. A better implementation on Windows would use named pipes
opened in asynchronous mode on the parent side and synchronous mode on
the child side. Just implement a loop that handles I/O completion
using events, APCs, or an I/O completion port.

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.46.1683744670.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27614&group=comp.lang.python#27614

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!newsreader4.netcologne.de!news.netcologne.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: dieter@handshake.de (Dieter Maurer)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Wed, 10 May 2023 20:51:02 +0200
Lines: 14
Message-ID: <mailman.46.1683744670.13552.python-list@python.org>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<25691.59286.327279.754535@ixdm.fritz.box>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de qXiIDOBbNPCkvpReq6AlLgl2MaKU7H0kHXUWq5gWiDuA==
Return-Path: <dieter@handshake.de>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=none reason="no signature";
dkim-adsp=none (unprotected policy); dkim-atps=neutral
X-Spam-Status: OK 0.011
X-Spam-Evidence: '*H*': 0.98; '*S*': 0.00; 'python.': 0.08; 'cc:addr
:python-list': 0.09; 'console,': 0.09; 'cc:no real name:2**0':
0.14; '*nix': 0.16; 'afterwards': 0.16; 'captured': 0.16; 'fetch':
0.16; 'pipe': 0.16; 'programm': 0.16; 'thread.': 0.16;
'variable.': 0.16; 'writes': 0.16; 'python': 0.16; 'implement':
0.19; 'cc:addr:python.org': 0.20; 'input': 0.21; 'i.e.': 0.22;
'run': 0.23; 'received:de': 0.23; 'cc:2**0': 0.25; 'output': 0.28;
'program': 0.31; 'think': 0.32; 'files,': 0.32; 'but': 0.32;
'there': 0.33; 'header:In-Reply-To:1': 0.34; 'files': 0.36;
'file': 0.38; 'could': 0.38; 'wrote': 0.39; 'files.': 0.40;
'want': 0.40; 'likely': 0.61; 'your': 0.64; 'header:Received:6':
0.67; 'subject:skip:s 10': 0.69; 'production': 0.71;
'implemented': 0.76; 'received:88': 0.84
In-Reply-To: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
X-Mailer: VM 8.0.12-devo-585 under 21.4 (patch 24) "Standard C" XEmacs Lucid
(x86_64-linux-gnu)
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <25691.59286.327279.754535@ixdm.fritz.box>
X-Mailman-Original-References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
 by: Dieter Maurer - Wed, 10 May 2023 18:51 UTC

Horst Koiner wrote at 2023-5-9 11:13 -0700:
> ...
>For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.

You might want to implement the functionality of the *nix programm
`tee` in Python.
`tee` reads from one file and writes the data to several files,
i.e. it multiplexes one input file to several output files.

Pyhton's `tee` would likely be implemented by a separate thread.

For your case, the input file could be the subprocess's pipe
and the output files `sys.stdout` and a pipe created by your own
used by your application in place of the subprocess's pipe.

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.47.1683750044.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27615&group=comp.lang.python#27615

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: mats@wichmann.us (Mats Wichmann)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Wed, 10 May 2023 14:20:29 -0600
Lines: 23
Message-ID: <mailman.47.1683750044.13552.python-list@python.org>
References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<25691.59286.327279.754535@ixdm.fritz.box>
<bab5e07c-97f5-fa67-52e3-10e072535efe@wichmann.us>
Mime-Version: 1.0
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Trace: news.uni-berlin.de bzDNO66FGeT/D9anVwPQQggKi6BoPK/K+7I7NIaRZ9ZQ==
Return-Path: <mats@wichmann.us>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="1024-bit key; unprotected key"
header.d=pobox.com header.i=@pobox.com header.b=bewy8c4R;
dkim-adsp=none (unprotected policy); dkim-atps=neutral
X-Spam-Status: OK 0.003
X-Spam-Evidence: '*H*': 0.99; '*S*': 0.00; 'internet,': 0.07;
'python.': 0.08; 'console,': 0.09; 'ended': 0.09; 'floating':
0.09; 'solving': 0.09; 'received:173': 0.13; '*nix': 0.16;
'afterwards': 0.16; 'captured': 0.16; 'dieter': 0.16; 'fetch':
0.16; 'pipe': 0.16; 'programm': 0.16; 'thread.': 0.16;
'variable.': 0.16; 'writes': 0.16; 'wrote:': 0.16; 'problem':
0.16; 'python': 0.16; 'implement': 0.19; 'to:addr:python-list':
0.20; 'input': 0.21; 'i.e.': 0.22; 'run': 0.23; "wasn't": 0.26;
'function': 0.27; 'output': 0.28; 'header:User-Agent:1': 0.30;
'program': 0.31; 'think': 0.32; 'files,': 0.32; 'but': 0.32;
'there': 0.33; 'particular': 0.33; "didn't": 0.34; 'header:In-
Reply-To:1': 0.34; 'files': 0.36; 'received:192.168': 0.37;
'file': 0.38; 'way': 0.38; 'could': 0.38; 'use': 0.39; 'wrote':
0.39; 'files.': 0.40; 'something': 0.40; 'want': 0.40; 'should':
0.40; 'likely': 0.61; 'once': 0.63; 'your': 0.64; 'choose': 0.67;
'subject:skip:s 10': 0.69; 'production': 0.71; 'reliable': 0.74;
'implemented': 0.76
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed; d=pobox.com; h=message-id
:date:mime-version:subject:references:from:to:in-reply-to
:content-type:content-transfer-encoding; s=sasl; bh=ebsxNrCfTotz
FyjZITWtYqvszOWmVn+dycw2wx4ynOI=; b=bewy8c4RJZjr0DDDgQyO5xxZCfIF
oZXfBcYP21vZkFkdhBzX1maPRoUJGDv3f4n37C5cRNNvQcm1MseAjbQIKkeGPB0C
4GWp8AzN/313gRQcCTZBB/IWttl5K6LJSbCVk2fyTUAt3BStOeSlO+vJ3nKsEi2A
15jxVpKKuvOqso0=
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed; d=wichmann.us;
h=message-id:date:mime-version:subject:references:from:to:in-reply-to:content-type:content-transfer-encoding;
s=2018-07.pbsmtp; bh=ebsxNrCfTotzFyjZITWtYqvszOWmVn+dycw2wx4ynOI=;
b=iRDlITdEbmxOPASce99bdWC91nzossA0OzU+6vupLuRHMj8EkYVQ0Mjx9pfltdDEIt9efvvyy5j/DDRz0ShonDcEEyqLZqyjzsWu2cfDrUC2YMaNA36W3OZJ+bZUIhDgN1M1npP2Gvph2FmA4Ee0K1Ow0IymWWYBtC3MwxurWBM=
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101
Thunderbird/102.10.0
Content-Language: en-US
In-Reply-To: <25691.59286.327279.754535@ixdm.fritz.box>
X-Pobox-Relay-ID: 1CAF8488-EF70-11ED-9AC8-C2DA088D43B2-81526775!pb-smtp20.pobox.com
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <bab5e07c-97f5-fa67-52e3-10e072535efe@wichmann.us>
X-Mailman-Original-References: <40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<25691.59286.327279.754535@ixdm.fritz.box>
 by: Mats Wichmann - Wed, 10 May 2023 20:20 UTC

On 5/10/23 12:51, Dieter Maurer wrote:
> Horst Koiner wrote at 2023-5-9 11:13 -0700:
>> ...
>> For production i run the program with stdout=subprocess.PIPE and i can fetch than the output later. For just testing if the program works, i run with stdout=subprocess.STDOUT and I see all program output on the console, but my program afterwards crashes since there is nothing captured in the python variable. So I think I need to have the functionality of subprocess.PIPE and subprcess.STDOUT sametime.
>
> You might want to implement the functionality of the *nix programm
> `tee` in Python.
> `tee` reads from one file and writes the data to several files,
> i.e. it multiplexes one input file to several output files.
>
> Pyhton's `tee` would likely be implemented by a separate thread.
>
> For your case, the input file could be the subprocess's pipe
> and the output files `sys.stdout` and a pipe created by your own
> used by your application in place of the subprocess's pipe.

should you choose to go this route, there are multiple efforts floating
around on the internet, worth a look. Don't know which are good and
which aren't. Went looking once to see if there was something to
replace a homegrown function that wasn't reliable - ended up solving
that particular problem a different way so didn't use any of the tees.

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<73e64816-7024-40e0-8b72-d3fcae7db945n@googlegroups.com>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27626&group=comp.lang.python#27626

  copy link   Newsgroups: comp.lang.python
X-Received: by 2002:a05:620a:2a07:b0:759:2fe:9931 with SMTP id o7-20020a05620a2a0700b0075902fe9931mr2575500qkp.15.1683910518066;
Fri, 12 May 2023 09:55:18 -0700 (PDT)
X-Received: by 2002:a4a:d095:0:b0:54f:8194:ff03 with SMTP id
i21-20020a4ad095000000b0054f8194ff03mr3705738oor.1.1683910517767; Fri, 12 May
2023 09:55:17 -0700 (PDT)
Path: i2pn2.org!i2pn.org!weretis.net!feeder8.news.weretis.net!feeder1.feed.usenet.farm!feed.usenet.farm!peer02.ams4!peer.am4.highwinds-media.com!peer03.iad!feed-me.highwinds-media.com!news.highwinds-media.com!news-out.google.com!nntp.google.com!postnews.google.com!google-groups.googlegroups.com!not-for-mail
Newsgroups: comp.lang.python
Date: Fri, 12 May 2023 09:55:17 -0700 (PDT)
In-Reply-To: <mailman.39.1683659154.13552.python-list@python.org>
Injection-Info: google-groups.googlegroups.com; posting-host=141.70.45.4; posting-account=BgXR-goAAABfh3D4rpbvVjOLIidKMlrh
NNTP-Posting-Host: 141.70.45.4
References: <9da63d82-55d2-bb0c-33d2-10b5d28a8dc8@wichmann.us>
<40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com> <mailman.39.1683659154.13552.python-list@python.org>
User-Agent: G2/1.0
MIME-Version: 1.0
Message-ID: <73e64816-7024-40e0-8b72-d3fcae7db945n@googlegroups.com>
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
From: koinerhorst6@gmail.com (Horst Koiner)
Injection-Date: Fri, 12 May 2023 16:55:18 +0000
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
X-Received-Bytes: 2644
 by: Horst Koiner - Fri, 12 May 2023 16:55 UTC

Using asyncio for this is a good possibility I was not aware of.

My best try with asyncio was:
import asyncio

async def run_command():
# Create subprocess
process = await asyncio.create_subprocess_exec(
'./test.sh',
stdout=asyncio.subprocess.PIPE, # Redirect stdout to a pipe
stderr=asyncio.subprocess.PIPE # Redirect stderr to a pipe
)

# Read stdout and stderr asynchronously
captured_output = b''
async for line in process.stdout:
print(line.decode().strip())
captured_output += line
async for line in process.stderr:
print(line.decode().strip())
captured_output += line

await process.wait()
print(captured_output)

# Run the asyncio event loop
asyncio.run(run_command())
########################################

This fulfills all my requirements. A nice to have would that the captured_output has not to be constructed with += 's but with a final seek(0) and read() of process.stdout. But I didn't find anything how to rewind the stream, that i can read the whole output again.
Another question is, if this solution is deadlock proof.

Thank you all for the already very valuable input!

Greetings,
Horst

Re: Do subprocess.PIPE and subprocess.STDOUT sametime

<mailman.59.1683927705.13552.python-list@python.org>

  copy mid

https://www.rocksolidbbs.com/devel/article-flat.php?id=27633&group=comp.lang.python#27633

  copy link   Newsgroups: comp.lang.python
Path: i2pn2.org!i2pn.org!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail
From: rosuav@gmail.com (Chris Angelico)
Newsgroups: comp.lang.python
Subject: Re: Do subprocess.PIPE and subprocess.STDOUT sametime
Date: Sat, 13 May 2023 07:41:31 +1000
Lines: 67
Message-ID: <mailman.59.1683927705.13552.python-list@python.org>
References: <9da63d82-55d2-bb0c-33d2-10b5d28a8dc8@wichmann.us>
<40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<mailman.39.1683659154.13552.python-list@python.org>
<73e64816-7024-40e0-8b72-d3fcae7db945n@googlegroups.com>
<CAPTjJmr16pEVT4zgsHJATQN9N3t572Ekodj=_Ck0UJYH1e338Q@mail.gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable
X-Trace: news.uni-berlin.de ubD71x/CR8ssDnErTXVm+gpd7/aaWWuhgXDYpGsP5hGw==
Return-Path: <rosuav@gmail.com>
X-Original-To: python-list@python.org
Delivered-To: python-list@mail.python.org
Authentication-Results: mail.python.org; dkim=pass
reason="2048-bit key; unprotected key"
header.d=gmail.com header.i=@gmail.com header.b=iyWt6+1W;
dkim-adsp=pass; dkim-atps=neutral
X-Spam-Status: OK 0.016
X-Spam-Evidence: '*H*': 0.97; '*S*': 0.00; 'this:': 0.03; 'def': 0.04;
'2023': 0.07; 'loop': 0.07; 'asynchronous': 0.09; 'skip:# 40':
0.09; 'import': 0.15; 'captured': 0.16; 'chrisa': 0.16;
'constructed': 0.16; 'fourth': 0.16; 'from:addr:rosuav': 0.16;
'from:name:chris angelico': 0.16; "it'd": 0.16; 'pipe': 0.16;
'rewind': 0.16; 'stdout': 0.16; 'was:': 0.16; 'wrote:': 0.16;
'to:addr:python-list': 0.20; 'sat,': 0.22; 'run': 0.23;
'anything': 0.25; 'task': 0.26; 'output': 0.28; 'whole': 0.30;
'question': 0.32; 'feed': 0.32; 'message-id:@mail.gmail.com':
0.32; 'but': 0.32; "i'm": 0.33; "didn't": 0.34; 'header:In-Reply-
To:1': 0.34; 'received:google.com': 0.34; 'close': 0.35; 'final':
0.35; 'from:addr:gmail.com': 0.35; 'processes': 0.36; 'really':
0.37; 'using': 0.37; "it's": 0.37; 'received:209.85': 0.37;
'could': 0.38; 'read': 0.38; 'received:209': 0.39; 'this,': 0.39;
'received:209.85.208': 0.39; 'still': 0.40; 'try': 0.40; 'event':
0.40; 'best': 0.61; 'here': 0.62; 'once': 0.63; 'events': 0.63;
'your': 0.64; 'independent': 0.65; 'guaranteed': 0.67; 'await':
0.69; 'scale': 0.69; 'subject:skip:s 10': 0.69; 'global': 0.73;
'(you': 0.76; 'perfect': 0.82; 'pipes': 0.84; 'redirect': 0.84
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=gmail.com; s=20221208; t=1683927703; x=1686519703;
h=content-transfer-encoding:to:subject:message-id:date:from
:in-reply-to:references:mime-version:from:to:cc:subject:date
:message-id:reply-to;
bh=W8l8Y7Ejl/0OJSb7vjf4lbeCAngLIOvXjsxxe7imkls=;
b=iyWt6+1Wl9qUdoiH2+cUElK8Jf01PO2E5s6xayJTP43kC8Thx4d8aicjp1VOiLSAJz
9/uizrnsHYY2ke0MTmuqCAv4HSto13hnILb4aP6CJqivifOWIEzAKhAv1VaUsOMHp41Y
+5Dw5K7tcZdeUZ+Kkz23n8mGUZFa3RQ9u4b4XTG/WnFMzf7StIwfpfT7Alvd2UrJVrxg
Gdn1ow2lx/Fl14WEIyeLetcTN+Y7X2p0dwWdOUTvZeCi7Y19UP5LOtUCeRG8gavx2SaT
rlmRY3Y1zZ98qDcvAx1S3Xu6FkxngEIFHmPcwpbgo1OGBM+0xjUZsmJn63+vVcK6DdC5
V8iA==
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
d=1e100.net; s=20221208; t=1683927703; x=1686519703;
h=content-transfer-encoding:to:subject:message-id:date:from
:in-reply-to:references:mime-version:x-gm-message-state:from:to:cc
:subject:date:message-id:reply-to;
bh=W8l8Y7Ejl/0OJSb7vjf4lbeCAngLIOvXjsxxe7imkls=;
b=AQJXSHBTTQKRxZNvcpvf65bWLZCT9pbVw1BPiibC7MUCtGk9k5DAxtAw94RCskH6li
uyTt71CKfekBLz1ONZcqF7bMJfHPIEs4fDD51Bpvo/ZMbH/8HiBj7byxPtnlpoLCSRHN
BqIyoTIGb5fctE6Tc53rWT/hdXQ3ZEpQb9NMTJmNvDbl1vqCHFv24wkvilKyFW59Ifko
PlTCSawUzhabjDyz2OnFHA3Nh8O7dNUoRU3lqzhRa6YJtmZVUKqaTU6UuqwyumRiAusQ
LXWqZ3ovKeqGjvfbIBZnhwXFhtcfXI9TgzCtdyM5TwdreVek43SFe176Q50jbhe8v5Fn
P5VQ==
X-Gm-Message-State: AC+VfDzRrmOW2gfWCEh6L4xyJlxdiEKj43pR312AVGSMSg6XhK6/jf2w
VaC1HVXLjpae42dRUFVRxapbLiEQ4k1yNucz8eJiMs3E
X-Google-Smtp-Source: ACHHUZ6WSA2Ok6eE0BzBAl60Zn8a2zwAA+VYOFqdrCkHizrTNwSabIWKw9PrOHGHnC5X6yUNYsqVCq+ap5Jf99qRfQc=
X-Received: by 2002:a17:907:2d0c:b0:966:5c04:2c5a with SMTP id
gs12-20020a1709072d0c00b009665c042c5amr19124120ejc.69.1683927702585; Fri, 12
May 2023 14:41:42 -0700 (PDT)
In-Reply-To: <73e64816-7024-40e0-8b72-d3fcae7db945n@googlegroups.com>
X-BeenThere: python-list@python.org
X-Mailman-Version: 2.1.39
Precedence: list
List-Id: General discussion list for the Python programming language
<python-list.python.org>
List-Unsubscribe: <https://mail.python.org/mailman/options/python-list>,
<mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive: <https://mail.python.org/pipermail/python-list/>
List-Post: <mailto:python-list@python.org>
List-Help: <mailto:python-list-request@python.org?subject=help>
List-Subscribe: <https://mail.python.org/mailman/listinfo/python-list>,
<mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID: <CAPTjJmr16pEVT4zgsHJATQN9N3t572Ekodj=_Ck0UJYH1e338Q@mail.gmail.com>
X-Mailman-Original-References: <9da63d82-55d2-bb0c-33d2-10b5d28a8dc8@wichmann.us>
<40d57d83-c868-4851-a01a-c5608f4924b1n@googlegroups.com>
<mailman.39.1683659154.13552.python-list@python.org>
<73e64816-7024-40e0-8b72-d3fcae7db945n@googlegroups.com>
 by: Chris Angelico - Fri, 12 May 2023 21:41 UTC

On Sat, 13 May 2023 at 07:21, Horst Koiner <koinerhorst6@gmail.com> wrote:
>
> Using asyncio for this is a good possibility I was not aware of.
>
> My best try with asyncio was:
> import asyncio
>
> async def run_command():
> # Create subprocess
> process = await asyncio.create_subprocess_exec(
> './test.sh',
> stdout=asyncio.subprocess.PIPE, # Redirect stdout to a pipe
> stderr=asyncio.subprocess.PIPE # Redirect stderr to a pipe
> )
>
> # Read stdout and stderr asynchronously
> captured_output = b''
> async for line in process.stdout:
> print(line.decode().strip())
> captured_output += line
> async for line in process.stderr:
> print(line.decode().strip())
> captured_output += line
>
> await process.wait()
> print(captured_output)
>
>
> # Run the asyncio event loop
> asyncio.run(run_command())
> ########################################
>
> This fulfills all my requirements. A nice to have would that the captured_output has not to be constructed with += 's but with a final seek(0) and read() of process.stdout. But I didn't find anything how to rewind the stream, that i can read the whole output again.
> Another question is, if this solution is deadlock proof.
>

No it's not, but the best part is, it's really close to! Asynchronous
I/O is perfect for this: you need to wait for any of three events
(data on stdout, data on stderr, or process termination). So here it
is as three tasks:

captured_output = b""
async def collect_output(stream):
global captured_output
async for line in stream:
print(line.decode().strip())
captured_output += line

(You can play around with other ways of scoping this, I'm just using a
global for simplicity)

Inside run_command, you can then spawn three independent tasks and
await them simultaneously. Once all three finish, you have your
captured output, and the process will have terminated.

This would then be guaranteed deadlock-proof (and, if you needed to
feed data on stdin, you could do that with a fourth task and it'd
still be deadlock-proof, even if it's more than one pipe buffer of
input), since all the pipes are being managed concurrently.

Even cooler? You can scale this up to multiple processes by calling
run_command more than once as separate tasks!

ChrisA


devel / comp.lang.python / Re: Do subprocess.PIPE and subprocess.STDOUT sametime

1
server_pubkey.txt

rocksolid light 0.9.81
clearnet tor