How to run shell commands within python

Discussion in 'Python' started by fileexit, Feb 16, 2006.

  1. fileexit

    fileexit Guest

    How can I execute shell commands from within python. Specifically, I
    am looking for something like the shell "cat". But this also made me
    wonder how to execute shell commands anyway, just if i needed to do
    that in the future.
    fileexit, Feb 16, 2006
    1. Advertisements

  2. fileexit

    Juho Schultz Guest

    You can use os.system() for that.
    Juho Schultz, Feb 16, 2006
    1. Advertisements

  3. fileexit

    limodou Guest

    You can use os.system() or os.popen(), etc.
    limodou, Feb 16, 2006
  4. fileexit

    fileexit Guest

    fileexit, Feb 16, 2006
  5. that's an old thread, and Python has grown a few more ways to
    deal with shell commands since then. if os.system isn't good en-
    ough for you, subprocess is the preferred alternative:

    (also note that most trivial shell commands are better done in
    python. most uses of cat, for example, can be trivially emulated
    with one or two lines of python...)

    Fredrik Lundh, Feb 16, 2006
  6. use subprocess module

    from subprocess import call
    call(['cmd', 'arg1', 'arg2'], stdin='...', stdout='...')
    call(['ls', '-l'])
    Szabolcs Nagy, Feb 16, 2006
  7. fileexit

    Donn Cave Guest

    Though the knowledge required to do this may be more trivial
    for some of us than others! "cat" probably doesn't have much
    going for it that a naive implementation would miss - some
    versions will recreate "holes", but most applications will never
    miss this. You can replace "mv" with os.rename() if you don't
    care that it will fail when the destination is on a different
    filesystem. Etc.

    Donn Cave,
    Donn Cave, Feb 16, 2006
  8. If you care than use `shutil.move()` instead.

    Marc 'BlackJack' Rintsch
    Marc 'BlackJack' Rintsch, Feb 17, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.