首页 > 解决方案 > os.popen 函数未分配给我的 var

问题描述

在这段代码中,我os.popopen用来运行后台系统命令。

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()

你会看到 user 首先等于 g,通常这等于 just (" ") 但我把它放到 g 来演示。我的代码应该正在运行我的fetch()函数,但它是以太失败 bts 或者我的函数没有被调用,因为用户总是等于函数之前的任何内容(在本例中为 g)。我在 python 控制台中运行了所有这些行,它在那里工作,这真的很令人沮丧。怎么了?

(在任何人谈论我应该如何使用之前subprocesses,这在我的情况下不起作用。)

标签: pythonfunction

解决方案


我认为这不是解决您的问题的最佳方法,但它可以使您的代码正常工作:

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)

我建议返回值,例如:

import os

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

user = get_os_user()
print(user)

如果你想从一个函数返回多个值,你可以:

import os

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

details = fetch_os_details()
print(details)

推荐阅读