How to import variable from Shell script in Python? - python

I have a Shell script, lets call it file.sh, that identifies a variable LOGFILE. I am trying to run a Python script calling the same variable, however it is not exporting properly.
I tried:
import os
print(os.environ(LOGFILE))
and got this error: name 'LOGFILE' is not defined
They are in the same directory, so I am not sure what the error is? How can I fix this?

The environment variable is not directly accessible as python variable. This is why you need to pass the name of the external environment-variable in the form of a string. Furthermore, environ is not a function, it is a dictionary, so you need to use square brackets to lookup 'LOGFILE' in the dictionary:
print(os.environ['LOGFILE'])
If you want a function that does something similar, use os.getenv()
print(os.getenv('LOGFILE'))

Related

Variable expansion in bitbake recipes

folks.
I've been studying yocto building process and I noticed the usage of the following structure:
PN = "${#bb.parse.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'}"
I know that ${} means variable expansion and grep command showed that the function "vars_from_file" is located at bitbake/lib/bb/parse/__init__.py.
I would like to understand how this variable expansion works, so I explored bitbake files and found out that:
oe-init-build-env calls oe-buildenv-internal, and the last one sets PYTHONPATH to bitbake/lib.
I'm infering that bitbake uses PYTHONPATH to search for the function vars_from_file
What I have not understood are:
the meaning of the symbol "#" in the variable expansion;
if bitbake uses PYTHONPATH to search for the function, why did not pass the absolute path ${#bb.parse.__init__.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'} instead of "${#bb.parse.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'}"
Is this type of variable expansion applied only in bitbake?. I searched in gnu website, and there is not the application of "#" in the beginning of the structures.
Can someone help me understand them?
The # symbol, is used bit bitbake for inline python variable expansion, and it basically states that you'd be calling a function and expanding its result, usually assigning it to a variable, in your case:
PN = "${#bb.parse.vars_from_file(d.getVar('FILE', False),d)[0] or 'defaultpkgname'}"
Its assigning to PN (package name) the result of the function vars_from_file coming from the bitbake python module parse, located at bitbake/lib/bb/parse/
Like any other Python module, it automatically loads init.py and has access to those functions when imported.
Whats special about these functions is that they've got access to bitbake's data dictionary, called "d".
AFAIC this IS specific to bitbake.

Adding new feature not working in pysandbox

I am using the pysandbox to run the Python code in sandbox environment. I got it up and running, but I want it to support python datetime module. As per the documentation, I added 'datetime' in the config as follows,
sandbox = SandboxConfig('datetime', cpython_restricted=False)
but if I run the code I still get the error,
'global name datetime is not defined'
There is some issue with the pysandbox. Looks like you are passing some parameter to the sandboxed function through the locals variable. In this case, the import is not added to the global namespace.
Simply write global datetime right after you import it and it will work. Otherwise, you may also pass it as a function parameter.

How do I access a variable value set by me in environment variables under system properties?

I created a new variable "sam" under system environment variables for current account and gave it a value as: "D:/My_folder/files/items". I need to fetch this path using python code. How can I do this? The code snippet below just returns my home directory:
print(os.environ['HOME'])
You can access Environment variables directly through os.environ to get complete list:
print(os.environ)
To access a specific path you need to enter a key from the path, just any word that exists in it. In your case, you can use "My_folder" for example. As follows:
print(os.environ['My_folder'])

Dyanamic/ Variable Filepath Python

I'm looking for a method of setting a variable in a path but I can't seem to find some way of doing this:
object = apps.[variable].main.run()
where variable is some string. Apps and Variable are two directories and main is a python script.
(For import statements I was able to use __import__(path))
Use getattr:
getattr(apps, variable).main.run()

python stdout and stderr: Am confused how my file object get passed to when i didn't declare global

I am having problem understand the sys.stdout and sys.stderr
The problem is how did the variable put get got into the cmd module?
My aim is to write a single function that would accept a string basically I am using it to write exception caught in my application to the screen and to a log file. I saw similar code somewhere so I decided to learn more by using the same example i saw which was a little different from my as the other person was writing to tow files simultaneously with just one function call.
According to my understanding:
The cmd module recieves a string which it then calls output module on the recieved string.
output module takes two arguements - (1 of its parameters must evalute to python standard input module object and second the a string) fine.
However, since output module calls logs module which does the printing or better still combines parameters by calling write function from python's standard output object passing it the string or text to be written.
Please if my explanation is not clear it means I am truely not understanding the whole process.
My questions is: How does put variable called outside the function got into the cmd module or any other module when I have commented it or not even called out?
Please find code below
`
import sys
def logs(prints, message):
#global put
#print prints
prints.write(message)
prints.flush()
def output(prints, message):
#global put
#logs(prints, content)
logs(prints, message)
#logs(put, via)
''' This is where the confusion is, how did put get into this function when i did
not declare it...'''
def cmd(message):
#global put
output(put, message)
output(sys.stderr, message)
put = open('think.txt', 'w')
#print put, '000000000'
cmd('Write me out to screen/file')
put.close()
`
Its because of the way that python handles scopes. When you execute the script, the logs, output and cmd functions are defined in the module namespace. Then put = open('think.txt', 'w') creates a variable called put in the module namespace.
When you call cmd, you are now executing in the function's local namespace. it is created when the function is called and destroyed when the function exits. When python hits the expression output(put, message), it needs to resolve the names output, put and message to see what to do with them. The rules for a function are that python will look for the name in the local function namespace and then fall back to the global module namespace if the variable is not found.
So, python checks the function namespace for output, doesn't find anything, looks at the module namespace and finds that output refers to a function object. It then checks the function namespace for put, doesn't find anything, looks at the module namespace and finds that put refers to an open file object. Finally, it looks up message, finds it in the function namespace (the function parameters go into the function namespace) and off it goes.
put is declared as a global variable, so when you access it from within cmd, it is accessing that global variable without you needing to declare it within the function.
For example, this code prints 5 for the same reason:
def foo():
print "bar: {0}".format(bar)
bar = 5
foo()

Categories