Python subprocess.Popen 结果存储在一个变量中 [英] Python subprocess.Popen result stored in a variable

查看:29
本文介绍了Python subprocess.Popen 结果存储在一个变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多其他关于这个的帖子,但不幸的是我仍然无法弄清楚这一点:

I've seen various other posts about this, but unfortunately I still haven't been able to figure this out:

如果我这样做:

temp = subprocess.Popen("whoami", shell=True, stdout=subprocess.PIPE)
out = temp.communicate()
print(out)

然后我得到一些形式

(b'username\n', None)

通过其他尝试(例如添加 .wait()),我在一行中获取用户名,在下一行获取 0 作为返回码,但是只有 0 存储在我的变量中.

With other attempts (such as adding a .wait()) I've been getting the username on one line, and a 0 as a return code on the next, however only the 0 was being stored in my variable.

有没有一种简单的方法可以格式化它以仅将用户名存储在变量中?我尝试了类似 out[3:11] 的方法,但没有奏效.

Is there an easy way I can format that to store only the username in a variable? I tried something like out[3:11] but that didn't work.

谢谢

推荐答案

最简单的方法是使用 subprocess.check_output():

The easiest way is to use subprocess.check_output():

username = subprocess.check_output("whoami").strip()

这篇关于Python subprocess.Popen 结果存储在一个变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆