empty stdout (subprocess.run)

11 views
Skip to first unread message

James Smith

unread,
Jan 19, 2022, 10:16:31 PMJan 19
to
I'm trying to run a shell command but the stdout is empty:

import subprocess

torrentno=8
cmd="/usr/bin/transmission-remote --torrent %s --info", str(torrentno)
res=subprocess.run(cmd, shell=True, check=True, universal_newlines=True, capture_output=True)
print(res)

CompletedProcess(args=('/usr/bin/transmission-remote --torrent %s --info', '1'), returncode=0, stdout='', stderr='')

Dennis Lee Bieber

unread,
Jan 19, 2022, 11:08:58 PMJan 19
to
On Wed, 19 Jan 2022 19:16:19 -0800 (PST), James Smith
<bjloc...@gmail.com> declaimed the following:

>I'm trying to run a shell command but the stdout is empty:
>
>import subprocess
>
>torrentno=8
>cmd="/usr/bin/transmission-remote --torrent %s --info", str(torrentno)

Don't you need to provide for that %s? Perhaps

cmd="/usr/bin/transmission-remote --torrent %s --info" % torrentno

As coded, you are passing a TUPLE of two strings as cmd (fyi: the %s will
take the string representation of whatever is the matching argument on the
right, so str() isn't needed -- and if you need a number for both --torrent
and --info you'll need another %s, and (torrentno, torrentno) on the right)

>res=subprocess.run(cmd, shell=True, check=True, universal_newlines=True, capture_output=True)
>print(res)
>
>CompletedProcess(args=('/usr/bin/transmission-remote --torrent %s --info', '1'), returncode=0, stdout='', stderr='')


--
Wulfraed Dennis Lee Bieber AF6VN
wlf...@ix.netcom.com http://wlfraed.microdiversity.freeddns.org/

Cameron Simpson

unread,
Jan 19, 2022, 11:14:28 PMJan 19
to
If you're using shell=True (please don't) you want cmd to be a string.
You have defined it as a 2-tuple. You can even see that in the
CompletedProcess object you printed.

I think you want to % substitue torrentno into the format string.

But I recommend you use shell=False and make:

cmd = ["/usr/bin/transmission-remote", "--torrent", str(torrentno), "--info"]

because assembling commands with % formatting is a recipe for injection
attacks. Look up "Little Bobby Tables", which is an SQL example of what
you're doing with the shell.

Cheers,
Cameron Simpson <c...@cskk.id.au>

James Smith

unread,
Jan 19, 2022, 11:19:09 PMJan 19
to
On Wednesday, January 19, 2022 at 11:08:58 PM UTC-5, Dennis Lee Bieber wrote:

> Don't you need to provide for that %s? Perhaps
>
> cmd="/usr/bin/transmission-remote --torrent %s --info" % torrentno

That works, thanks.

James Smith

unread,
Jan 19, 2022, 11:26:11 PMJan 19
to
On Wednesday, January 19, 2022 at 11:14:28 PM UTC-5, cameron...@gmail.com wrote:

> But I recommend you use shell=False and make:
>
> cmd = ["/usr/bin/transmission-remote", "--torrent", str(torrentno), "--info"]

I like that. :-)
Reply all
Reply to author
Forward
0 new messages