How to call an external command in Python?

Report
Question

Please briefly explain why you feel this question should be reported .

Report
Cancel

Want to call an external command using Python.

For example, execute ls -l through a Python script.

 

solved 0
Python 5 months 1 Answer 508 views 0

About sofia

Answer ( 1 )

  1. rg123

    Please briefly explain why you feel this answer should be reported .

    Report
    Cancel

    There are different ways to call external programs:
    You can use os.system(command) to execute the command (a string) in a subshell.
    Availability: Unix, Windows.
    On Unix, the return value is the exit status of the process encoded in the format specified for wait().
    On Windows, the return value is that returned by the system shell after running a command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation.
    Example :

    import os
    print(os.system("ls -l"))
    

    or
    you can use subprocess module
    The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

    os.system
    os.spawn*

    Example :

    from subprocess import call
    print(call(["ls", "-l"]))
    
    Best answer

Leave an answer

Browse

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>