os.popen('alias')

B

Belebele

From an interactive python shell, I execute the following:

import os
for line in os.popen('alias').readlines():
print line


No aliases are printed.

I started python from an bash environment that had many aliases
defined. I expected to see the list of aliases from within the
interactive python shell. What could I do to see those aliases defined
in the shell from where I started python?

Thanks:

Belebele
 
L

Lars Kellogg-Stedman

import os
for line in os.popen('alias').readlines():
print line


No aliases are printed.

I started python from an bash environment that had many aliases
defined. I expected to see the list of aliases from within the
interactive python shell. What could I do to see those aliases defined
in the shell from where I started python?

You can't, really. The 'alias' command is a shell built-in, not an external
command, so you can't meaningfully run it from a Python script (and any
aliases defined in your shell will probably not be available to Python).

Matters are complicated a little bit because when you use os.popen(),
your command line is actually passed to *a* shell, usually /bin/sh, so
the final command line looks like this:

/bin/sh -c 'alias'

However, even if /bin/sh is actually bash, dotfiles such as .profile and
..bashrc aren't read when using the '-c' option.

If you really want to do something to your bash aliases with python, you
could pipe them into a python command:

$ alias | python myscript.py

-- Lars
 
C

Chris F.A. Johnson

import os
for line in os.popen('alias').readlines():
print line


No aliases are printed.

I started python from an bash environment that had many aliases
defined. I expected to see the list of aliases from within the
interactive python shell.

Since bash does not export aliases, they cannot be seen by a child
process.
What could I do to see those aliases defined in the shell from where
I started python?

Store them in a file before calling python, and read that file.
 
C

Chris F.A. Johnson

Since bash does not export aliases, they cannot be seen by a child
process.


Store them in a file before calling python, and read that file.

Or redefine them as functions and use:

import os
for line in os.popen('typeset -f').readlines():
print line
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,202
Latest member
MikoOslo

Latest Threads

Top