Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from command line from within a Python program?

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')?

like image 276
user1058492 Avatar asked Nov 21 '11 19:11

user1058492


People also ask

How read data from command line in Python?

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().

How do you access command line arguments in Python?

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.

How do I get text from console in Python?

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.


1 Answers

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.

like image 198
koblas Avatar answered Sep 19 '22 20:09

koblas