如何从Python中的环境变量获取可执行文件的路径? [英] How to get the path to an executable from its environment variable in Python?

查看:471
本文介绍了如何从Python中的环境变量获取可执行文件的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    您好,

我正在处理python代码并要求打开位于的可执行文件我的C盘。我不想编写类似的东西,

file = open(C:\\Documents\\CodeRepo ... \\codeplay.exe)

我想使用名为LOCATION_HOME的环境变量来指向这个exe位置。

我不知道我什么时候设置这个环境变量。我是在我的python代码中设置它还是使用终端在Windows?

有人可以告诉我如何做到这一点。

提前致谢。





我尝试了什么:



我试着按照以下方式做。我创建了环境变量LOCATION_HOME指向
C:\\Documents\\CodeRepo ...然后我在python代码中执行了file = open(LOCATION_HOME \\codeplay.exe)。

它找不到错误文件。

解决方案

你可以通过谷歌搜索轻松找到答案如何在python中解析环境变量。

您必须在启动Python脚本的同一终端中设置(手动或使用其他脚本或批处理文件)或全局设置(搜索windows set permanent environment variable)。



然后使用

  import  os 

path = os.environ [ LOCATION_HOME]



参见 16.1。 os - 其他操作系统接口 - Python 3.6.1rc1文档 [ ^ ]。


Hi,

I am working on a python code and require to open an executable which is located in my C drive. I dont want to code something like, 

    file = open("C:\\Documents\\CodeRepo...\\codeplay.exe)

I want to use the environment variable called LOCATION_HOME to point to this exe location.

I dont know when do i set this environment variable. Do i set it in my python code or using the terminal in Windows?

Can someone please provide me insight on how to do this.

Thanks in advance.



What I have tried:

I tried to do as follows. I created an environment variable LOCATION_HOME which points to
C:\\Documents\\CodeRepo... and then I did file = open("LOCATION_HOME\\codeplay.exe") in python code. 

It gives error file not found.

解决方案

You could have easily found the answer yourself just by Googling for "How to resolve an environment variable in python".


You have to set in the same terminal from where your Python script is started (manually or using another script or batch file) or set it globally (search for "windows set permanent environment variable").

Then use

import os

path = os.environ["LOCATION_HOME"]


See also 16.1. os — Miscellaneous operating system interfaces — Python 3.6.1rc1 documentation[^].


这篇关于如何从Python中的环境变量获取可执行文件的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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