简体   繁体   中英

How to Store the Output of a system return function in a string variable in python/tkinter

Query: How to store the output of a os.system return function into a string variable ?

I tried the below code but it always prints '0'

  1. Not declared the user_name as StringVar()
  2. Used the below code to find the user name.

    user_name = os.system("ypcat passwd | grep $USER | awk -F ':' '{print $5}'")

  3. I tried printing as print user_name , but it prints '0'.
  4. And also wherever I use the user_name as variable to substitute with the user name its printing as '0'.

Can you kindly share your inputs/comments how to store the output of the system call in python ?

os.system() returns the exit code of the executed command, so it makes sense that this is 0. If you want to store the output of the executed command, you should probably use subprocess.check_output() from the Subprocess Module .

As previously mention, you are getting the return code from the command that you issued but there has to be an easier way to get the user name than the one that you are using.
There are multiple ways of doing it but one of the easiest is:

import os
user_name = os.environ['USERNAME']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM