0

Is it possible to run python script as if it's a command line interpreter, Example :

from sys import argv

argv=argv[1:]
str=''.join(argv)
import os
def ls():
    x=os.listdir(os.getcwd())
    for file in x:
        print(file)
if str =='ls':
    ls()

in this case I used argv to pass arguments, but can I want the code to behave like a command line interpreter and call my functions example:

myscript> ls file.py myscript>

Note :Sorry if i didn't explain my idea clearly, English is not my native language.

Update : some people said my question is duplicated and the same question of this but i repeat , I want to make "interactive shell" not "How to execute Python scripts in Windows"

Community
  • 1
  • 1
  • If you run the Python interpreter, you can import a file and run is that way. Is that what you're looking for? –  Feb 02 '16 at 16:43
  • No, what i want is to run the script as an external program , the script calls the functions you created in the script but without "()" of the function, the best word to describe what i want is "interactive shell" – Hassan Abdul-Kareem Feb 02 '16 at 16:47
  • not really, here i am trying to make interactive shell not "how to pass arguments correctly" guys let me explain more, when you open cmd you type ls/dir (depending on the os) to run the command , and then the cmd continues to execute the next command the user enter that's what i mean't. – Hassan Abdul-Kareem Feb 02 '16 at 17:01

3 Answers3

2

After a long search i found a module named cmdln which provides the best functions to do such tasks , Example :

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    def do_greet(self, line):
        print ('hello')

    def do_EOF(self, line):
           #this command will make you exit from the shell
        return True

if __name__ == '__main__':
    HelloWorld().cmdloop()

When you run the script , It will be like:

(Cmd) greet
hello
(Cmd) print
string
(cmd) EOF

Then the shell will stop , Thanks for everyone who tried to help me.

2

If I understood you correctly, You want a REPL which can functions like your own version of ls using python. This answer is based on above assumption.

People have done that actually, for instance xonsh using python-prompt-toolkit. Would like to suggest you to use a framework to reduce development time. If you want to do from scratch, Idea is to use loop waiting for command, execute the function, print and then wait

dlmeetei
  • 9,905
  • 3
  • 31
  • 38
-2

Yes, check about hashbang

Basically, you just have to add this as first line in your file

#!/usr/bin/env python

also change file mode to executable

chmod +x yourfile.py

And you'll able to execute the file as a regular command. The point is that under the hood it just calls appropriated interpreted for your file (and using hashbang you just specify needed interpreter).

Akisame
  • 754
  • 7
  • 16