如何使用子进程在 Python 中访问 Bash 环境变量? [英] How to access Bash environment variable in Python using subprocess?

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

问题描述

我可以在 Python 中使用 subprocess-handled 查询来确定终端的宽度,如下所示:

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 用户名?那么,如何使用子进程在 Python 中查看 ${USER} 的值?

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 和 dano 所说,不要为此使用子进程.使用 os.getenv("USER")os.environ["USER"].

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

如果你真的想使用 subprocess 那么 Popen(['bash', '-c', 'echo "$USER"'], ...)似乎和 Popen("echo $USER", shell=True) 一样工作,尽管这两个都不是特别愉快(尽管在正在执行的命令行上使用环境变量,必须涉及到 shell,所以你真的无法避免).

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

我之前的子流程建议似乎没有正常工作.我相信我最初的测试有缺陷.

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

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

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