使用Python中的子进程访问的Bash环境变量 [英] access Bash environment variable in Python using subprocess

查看:852
本文介绍了使用Python中的子进程访问的Bash环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能确定在Python终端与子进程,处理查询的宽度,如下列:

I can determine the width of the terminal in Python with a subprocess-handled query such as the following:

int(subprocess.Popen(['tput', 'cols'], stdout = subprocess.PIPE).communicate()[0].strip('\n'))

我怎么能确定以类似的方式Bash的用户名?那么,如何可以用子我看到的$ {USER}值在Python?

How could I determine the Bash user name in a similar way? So, how could I see the value of ${USER} in Python using subprocess?

推荐答案

由于Wooble和端午说,不使用子这一点。使用 os.getenv(用户) os.environ [USER]

As Wooble and dano say, don't use subprocess for this. Use os.getenv("USER") or os.environ["USER"].

如果你真的想使用然后 POPEN(['庆典','-c','回声$ USER'] ,...)似乎工作一样 POPEN(回声$ USER,壳=真)虽然这些都不是特别愉快(虽然在命令行上使用的环境变量正在执行的外壳必须参与,所以你真的不能避免的话)。

If you really want to use subprocess then Popen(['bash', '-c', 'echo "$USER"'], ...) seems to work as does Popen("echo $USER", shell=True) though neither of those is particularly pleasant (though to use environment variables on the command line being executed the shell must be involved so you can't really avoid it).

编辑:我的previous子的建议似乎并没有正常工作。我相信我原来的测试是有缺陷的。

My previous subprocess suggestion did not seem to work correctly. I believe my original test was flawed.

这篇关于使用Python中的子进程访问的Bash环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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