如何运行“来源” python的命令?

发布于 2025-02-10 01:24:32 字数 400 浏览 3 评论 0原文

我需要通过Python来采购以下文件来设置ROS2 Galactic环境: -

“ source/opt/ros/galactic/setup.bash”,

如果我在终端中编写上述行,它将被来源,但我需要从Python脚本。

我尝试了: -

import subprocess
subprocess.call("source /opt/ros/galactic/setup.bash", shell=True)

import os
os.system('source /opt/ros/galactic/setup.bash')

它们都没有采购环境。我正在ubuntu 20.04,Python 3.8.10。

I need to set up the ROS2 Galactic environment by sourcing the following file through python: -

"source /opt/ros/galactic/setup.bash"

If I write the above line in terminal it will be sourced but I need to do this from python script.

I tried: -

import subprocess
subprocess.call("source /opt/ros/galactic/setup.bash", shell=True)

and

import os
os.system('source /opt/ros/galactic/setup.bash')

But none of them is sourcing the enviornment. I am working on Ubuntu 20.04, Python 3.8.10.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

这不会影响您的Python运行时环境。子过程启动一个外壳,其中它运行您的脚本(setup.bash),然后终止。

考虑一下:

import subprocess
import os

subprocess.run('export FOO=1', shell=True)
print(os.environ['FOO'])

这试图在子壳中设置环境变量。实际上有效,但是当run()返回时,壳不再存在。因此,当我们尝试访问环境变量时,我们会得到keyError

This will not impact your Python runtime environment. subprocess starts a shell wherein it runs your script (setup.bash) and then terminates.

Consider this:

import subprocess
import os

subprocess.run('export FOO=1', shell=True)
print(os.environ['FOO'])

This tries to set an environment variable in the sub-shell. That actually works but when run() returns, the shell no longer exists. Thus, when we try to access the environment variable we get KeyError

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文