I want to run a command line program from within a python script and get the output.
How do I get the information that is displayed by foo so that I can use it in my script?
For example, I call foo file1
from the command line and it prints out
Size: 3KB Name: file1.txt Other stuff: blah
How can I get the file name doing something like filename = os.system('foo file1')
?
The Python Console accepts command in Python which you write after the prompt. User enters the values in the Console and that value is then used in the program as it was required. To take input from the user we make use of a built-in function input().
To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.
To read a string from console as input to your Python program, you can use input() function. input() can take an argument to print a message to the console, so that you can prompt the user and let him/her know what you are expecting.
Use the subprocess module:
import subprocess command = ['ls', '-l'] p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.IGNORE) text = p.stdout.read() retcode = p.wait()
Then you can do whatever you want with variable text
: regular expression, splitting, etc.
The 2nd and 3rd parameters of subprocess.Popen
are optional and can be removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With