0

In this code, I am using os.popopen to run a background system command.

import os
user = "g"

def fetch(): # Gets all the system info via os.system and stores them in variables 
     user = os.popen("""whoami""").read()
fetch()
print(user)
input()

You will see that user is first equal to g, normally this is equal to just (" ") but I put it to g to demonstrate. My code should be running my fetch() function but it is ether failing bts or my function is not being called, beucase user is always equal to whatever it was before the function (in this case, g). I ran all these lines in the python console and there it works, which makes this really frustrating. What is happening?

(before anyone says anything about how I should be using subprocesses, that does not work in my case.)

Gizmoz
  • 13
  • 3

1 Answers1

1

I don't think this is the best approach to solve your problem but it makes your code work:

import os
user = "g"

def fetch(): # Gets all the system info via os.system and stores them in variables
    global user 
    user = os.popen("""whoami""").read()
fetch()
print(user)

I'd suggest returning the value, for example:

import os

def get_os_user():
    return os.popen("whoami").read()

user = get_os_user()
print(user)

If you want to return multiple values from a single function you could:

import os

def fetch_os_details():
    return {
        "user": os.popen("whoami").read(),
        "pwd": os.popen("pwd").read(),
    }

details = fetch_os_details()
print(details)
luigibertaco
  • 827
  • 4
  • 19
  • 1
    This would be a much better answer if you explained *why* the OP's code doesn't work (e.g. a brief overview of the rules for when a name is local vs. global). – ShadowRanger Nov 27 '19 at 00:10
  • 1
    For the record, on multiple returns, [the typical way of doing it is via `tuple`s, not `dict`s](https://stackoverflow.com/q/354883/364696). If you really want to return with names, you'd make a `collections.namedtuple`/`typing.NamedTuple` type outside the function to return instances of (so you can access the result either by name or by unpacking like a plain `tuple`). – ShadowRanger Nov 27 '19 at 00:12