0

I have the following python script

        get = int(subprocess.run(["electrum","getbalance"]))
          if get > 0:
          print("something")

I get the following error TypeError: int() argument must be a string, a bytes-like object or a number, not 'CompletedProcess'

The output of getbalance is : { "confirmed": "0.000001" }

How can i compare if the balance is higher then 0 and print something ?

  • I don`t understand why do you try to convert subprocess.run to integer. Can you upload the whole code? – vojtam Sep 01 '21 at 08:58
  • 2
    Possible duplicate or related - [subprocess.run().stdout.read() returns CompletedProcess not a string](https://stackoverflow.com/q/65540013/1324033) – Sayse Sep 01 '21 at 08:59
  • 1
    Use `subprocess.check_out` instead. A byte-object will return if the execution is successful. – HALF9000 Sep 01 '21 at 09:16

2 Answers2

1

The run function returns an instance of subprocess.CompletedProcess class.

As per the documentation, you can use stdout property to get the Captured stdout from the child process. Note that this will return a bytes sequence(Since run() was not called with an encoding, errors, or text=True)

Also to to capture the stdout and stderr pass capture_output=True to run function.

Example:

>>> from subprocess import run
>>> completed_process = run(['powershell.exe', '-c', 'Write-Output "Hello"'], capture_output=True)
>>> type(completed_process)
<class 'subprocess.CompletedProcess'>
>>> completed_process.stdout
b'Hello\r\n'
>>> type(completed_process.stdout)
<class 'bytes'>
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
1

I think this should do the trick:

output = subprocess.run(your_command_here, capture_output=True, text=True)

This will return a "CompletedProcess". Then you can check if everything went good doing:

if(output.returncode == 0):
    # do stuffs

And looking at the output you say your command is returning { "confirmed": "0.000001" } I guess python will use it as a JSON. So you can get the "0.000001" value with:

import json
data = output.stdout
data = json.loads(data)
what_you_want = data['confirmed']

So the code looks like this:

import json
output = subprocess.run(your_command_here, capture_output=True, text=True)
if(output.returncode == 0):
    data = output.stdout
    data = json.loads(data)
    what_you_want = data['confirmed']

PS: I did not try this code, I don't know if it runs.

FORGISDELUXE
  • 103
  • 1
  • 6