2

I'm trying to create a function which returns output as the command would be written into the command line in Windows or Linux?

EXAMPLE:

def cmd_simulator(commands):
    #some code

cmd_simulator("date")

- Thu Jan 28 12:18:05 EST 2016

or Windows:

cmd_simulator("date")

- The current date is: Thu 01/28/2016
- Enter the new date: (mm-dd-yy)
3
  • 1
    Do you want to delegate your commands to the console shell? Commented Jan 28, 2016 at 17:10
  • 3
    subprocess.check_output may be be useful to you. Commented Jan 28, 2016 at 17:11
  • cmd_simulator=lambda cmd:os.popen(cmd).read();print cmd_simulator("date") Commented Jan 28, 2016 at 17:14

2 Answers 2

2

You need to use the subprocess module in order to deal with command lines inside a python script. If the only thing you need is to get the output of your command, then use subprocess.check_output(cmd).

cmd is a sequence (python list) of program arguments. So, if your command only contains one word (such as date), it will work using cmd="date". But if you have a longer command (for example cmd="grep 'pattern' input_file.txt"), then it will not work, as you need to split the different arguments of your command line. For this, use the shlex module: shlex.split(cmd) will return the appropriate sequence to subprocess.

So, the code for your cmd_simulator would be something like:

import subprocess
import shlex

def cmd_simulator(cmd):
    return subprocess.check_output(shlex.split(cmd))

And of course, you can add to this function some try/except to check that the command is working, etc.

If you don't only need the stdout of your command but also stderr for example, then you should use subprocess.Popen(cmd).

Sign up to request clarification or add additional context in comments.

Comments

0

You can use this method-

import subprocess

cmd_arg = "date"
proc = subprocess.Popen(cmd_arg,  stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = proc.communicate()

print(out) #Thu Jan 28 12:18:05 EST 2016

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.