Python Forum

Full Version: How to get from linux command line to an array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I am a totally newby.

I am trying to convert from Linux Bash to python. 

I need the output of Linux commands to be stored in a Python array.


######################################
PythonArray <   ls -lar
 
for X in (PythonArray):
    print X
######################################


this is not real code as you know however I hope it explains what I need. 

If I am not clear, feel free to ask me to clarify
Working with processes tends to be kind of a pain. Do you actually want a list ("Python array") of the lines of a Bash command, or is that an implementation detail for something else you actually care about? Writing it in pure Python without messing with Bash would probably be better.
(Dec-04-2016, 11:51 PM)timfox123 Wrote: [ -> ]Hello, I am a totally newby.

I am trying to convert from Linux Bash to python. 

I need the output of Linux commands to be stored in a Python array.


######################################
PythonArray <   ls -lar
 
for X in (PythonArray):
    print X
######################################


this is not real code as you know however I hope it explains what I need. 

If I am not clear, feel free to ask me to clarify

Python 3
import subprocess

def main():
    process = subprocess.Popen(['ls', '-lar'], stdout=subprocess.PIPE)
    out, err = process.communicate()
    #print(out)
    # decode bytes to python string
    out = out.decode('utf-8')
    #print(out)
    # convert to python list
    out = out.split('\n')
    #print(out)
    for o in out:
        print(o)    

if __name__ == "__main__":
    main()
There are also python commands to do things like "ls" much easier, if you intend to parse the outputs, etc. Welcome to python! :)
Thank you all !!!!

this will do it