[Tutor] invoking system commands from python

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 30 21:36:58 CEST 2004

On Wed, 29 Sep 2004, Fulvio Copex wrote:

> i'm new to this list and to python too.
> I'm using active state python 2.3 on win32,
> my problem is the following:
> I want learn how to execute system command passing parameters.
> for example to copy a file I've tried to write this script:
> *****************************
> import os
> os.chdir(''myDirectory")
> cmd="copy"
> parameters="file1 file1_backup"
> myCmd = os.popen(cmd,'w')
> myCmd.write(parameters)
> exitCode = myCmd.close()
> if exitCode:
>     print '%s failed, this probably says why:\n%s' % (cmd, myCmd)

Hi Fulvio,

There's a syntax problem here:

> os.chdir(''myDirectory")

but you probably have fixed this already.  There's a more important
problem in the use of os.popen():

> myCmd = os.popen(cmd,'w')
> myCmd.write(parameters)

Your 'copy' command may need to take in the parameters at the same time as
the popen call, as additional "command-line arguments".  I'm not sure how
your 'copy' command works, but it may not be listening to standard input.

So you may need to do something like this:

    os.popen("%s %s" % (cmd, parameters))

where we construct the command line all at once, and then pass that off to

That being said, when you're programming in Python, you actually want to
avoid using os.popen() or os.system() if you can help it.  *grin*

The reason is because they're really OS-specific: you can't then take the
same program on Windows and expect it to work on a Unix system, at least,
not without a lot of work.  It's also fraught with security problems.

There's already a file-copying function in the 'shutil' shell utilities
module in the Standard Library:


So a better way to do file copying is to use shutils.copy().

import os
import shutils
shutils.copy("file1", "file1_backup")

Not only is this easier to read, but it should be much more portable
across operating systems.

If you have more questions, please feel free to ask.  Good luck!

More information about the Tutor mailing list