Milano
Milano

Reputation: 18725

How to create "cmd" function in Python?

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)

Upvotes: 2

Views: 134

Answers (2)

COD3R
COD3R

Reputation: 129

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

Upvotes: 0

pip
pip

Reputation: 185

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

Upvotes: 2

Related Questions