How can I delay execution until after os.system fi

2019-03-04 03:15发布

问题:

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.

回答1:

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.



回答2:

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

(Edit: woops, copy, not move)



回答3:

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.