Assign Linux environment variable in python

Asked

Viewed 491 times

-1

I need to read an environment variable in Linux, and store it in a variable in Python. I’ve tried it in many ways and failed.

I started with this command, on linux $variavel='123123'

x = os.system('echo $variavel')

print('{}'.format(x))  #~~> que resulta em 0

but with research I found that he will basically say that the command worked or not.

What is the command so that I can store the variable value and use it in the code later? I’ve read the library documentation os, but still I’m having difficulties, someone could give me a strength?

1 answer

1

The module os has a dictionary with environment variables that can be accessed by os.environ. If your environment has the variable PATH and you want to access it via Python just do:

import os
PATH = os.environ['PATH']
  • was perfect, I had tried with this option, but the error was in the same Linux environment variable... Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.