Search code examples
pythonpython-2.7python-3.xterminalmacos-sierra

How do I let Python see what Terminal outputs when I enter a command?


I want to run a program on Python on macOS Sierra that checks Terminal for its outputs after I automatically enter a command on it. For example, I would write in Terminal:

$ pwd

and then Terminal would output something like:

/Users/username

How would I have Python scan what Terminal outputs and set it to a variable as a string?

>>>output = (whatever Terminal outputs)
>>>print (output)
"/Users/username"

By the way, the other forums do not explain in much detail how one would do this in macOS. Therefore, this is not a duplicate of any forum.


Solution

  • You could pipe the output to a file and read the file.

    $ pwd > output.txt
    

    Then read the file and take further actions based on its contents.