简体   繁体   English

如何在python / tkinter中的字符串变量中存储系统返回函数的输出

[英]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 ? 查询:如何将os.system返回函数的输出存储到字符串变量中?

I tried the below code but it always prints '0' 我尝试了下面的代码,但它始终显示“ 0”

  1. Not declared the user_name as StringVar() 未将user_name声明为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'. 我尝试使用print user_name ,但是它打印为“ 0”。
  4. And also wherever I use the user_name as variable to substitute with the user name its printing as '0'. 而且无论我在哪里使用user_name作为变量来替换为用户名,其打印为“ 0”。

Can you kindly share your inputs/comments how to store the output of the system call in python ? 您能否好好分享您的输入/评论,以及如何在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 . os.system()返回已执行命令的退出代码,因此它为0是有意义的。如果要存储已执行命令的输出,则可能应该使用Subprocess Modulesubprocess.check_output subprocess.check_output()

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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