ramdaz
ramdaz

Reputation: 1791

How can I delay execution until after os.system finishes?

I am using os.system to copy a file from a system to another. The logic of a very simple program is to execute another set of commands after this file gets copied.

The problem is that os.system does not actually wait for the file to be copied, and gets to executing the next line. This causes issues to the system. I could actually give some wait functions, through time.sleep(), but we have to copy files with sizes ranging from 500 MB to sometimes 20 GB, and the times taken are very different.

What's the solution? I need to somehow tell my program that the files are copied, and then to execute the next line.

Upvotes: 1

Views: 5803

Answers (3)

Corey Goldberg
Corey Goldberg

Reputation: 60624

use the shutil module for copying files.

The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal.

also, use the subprocess module instead of os.system()

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 other, older modules and functions, such as:

os.system

for a better answer, you need to provide more detail about what exactly you are trying to do and how (programmatically) you are stuck.

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602235

The first thing I'd try is to use shutil.copyfile() instead of an external program to copy the file. If you have to use an external program, you should call it via subprocess.Popen(), not via os.system(). You can use the Popen.wait() to wait for the subprocess to finish.

Upvotes: 6

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

I think you should rather use shutil.copyfile than os.system to copy a file.

(Edit: woops, copy, not move)

Upvotes: 1

Related Questions