0

I'm playing around with what should be a simple script. I've goa bash script one line that just runs an API call to a server I have. I've got a py3 script that calls that bash script in a function and returns the output.

I'm then setting a variable equal to the function, and finally printing that variable.

For some reason even though im not directly calling the function (I guess I am when im declaring my variable) it's running the function anyway, and my variable's value is set to 0.

I've tried it a couple different ways and set it up similar to how some of the posts on here have said but I just dont understand why it's doing this.

#!/usr/bin/env python3

import subprocess


def api_call():
    return subprocess.call("/home/gposcl1/PyNetBox/api_GET.sh")
    
print("")
print("")
print("")

api_call_result = api_call()

print("")
print("")
print("")

print(api_call_result)

This is the output im getting. I've changed the output of the API call as it's rather unipmortant to the question and contains sensitive data:

$  
$ ./var1.py            



{"count":3,"next":null,"previous":null,"results":[{"id":31689,"url":,"role":null,"is_pool":false,"description":"1234_lower","tags":[],"custom_fields":{},"created":"2021-02-05","last_updated":"2021-02-05T06:20:16.733088Z"}]}


0
$
Sean Liles
  • 55
  • 2
  • 8

2 Answers2

1

If you use run instead of call, you can set capture_output to True and then retrieve stdout:

def api_call():
    r = subprocess.run("/home/gposcl1/PyNetBox/api_GET.sh", capture_output=True)
    return r.stdout.decode()
joao
  • 2,220
  • 2
  • 11
  • 15
-1
#!/usr/bin/env python3

import subprocess


def api_call():
    r = subprocess.run("/home/gposcl1/PyNetBox/api_GET.sh", stdout=subprocess.PIPE)
    return r.stdout


print("")
print("")
print("")

api_call_result = api_call()

print("")
print("")
print("")

print(api_call_result)
Sean Liles
  • 55
  • 2
  • 8