Dan Alexander
Dan Alexander

Reputation: 2072

Turn python input into command

I am working on making my own shell but what I want it to do what the user input.

For Example:

while 1:
    c = input()
    do c

By do c I want it to then do the command that the person put in.

Any Ideas,

Thanks In Advance!

Upvotes: 1

Views: 292

Answers (2)

rjv
rjv

Reputation: 6766

You can use the following:

system

system() from os moduule executes a command supplied as an argument and returns the return code.

import os
cmd=raw_input()
os.system(cmd)    

popen

popen is used to create a subprocess.The advantage is that popen can be used to read the output of a command executed.

import os
cmd=raw_input()
l=os.popen(cmd)
print l.read()

Upvotes: 0

jamylak
jamylak

Reputation: 133554

Assuming you are using Python 3, on Python 2 you would use raw_input instead

while 1:
    c = input()
    exec(c)

note that you can't trust that people won't enter malicious code here

You may also want to wrap this in a try/except to print the traceback when an Exception occurs and continue the loop:

import traceback
while 1:
    try: 
        c = input()
        exec(c)
    except:
        print(traceback.format_exc())

Upvotes: 1

Related Questions