How can a file be copied in Python? Part- III
Using the subprocess module
In this article let’s learn ways to copy a file using the subprocess module. This module replaces some methods in the os module, in particular the os.system() method.Make sure you learn about the shutil module, the os module and their methods before we dive into this article.
This module has two main methods to access the operating system commands for file copying.
- call()
- check_output()
let’s discuss each one of these methods in detail.
1. Using call():
This method is much similar to the os.system() method which directly calls or runs the command passed as an argument to the function. We can launch a command directly from the operating system.
The syntax of call() is as follows
Example:
subprocess.call(args, *, stdin=None, stdout=None, shell=False)
Output:
args is the shell command used.
The use of shell=True would be a security risk as per the Python documentation.
Example:
For Linux:
import subprocess subprocess.call('cp source_file.txt destination_file.txt', shell=True)
For Windows
import subprocess subprocess.call('copy source_file.txt destination_file.txt', shell=True)
Output:
2. Using check_output():
This method also executes a command within a shell It, by default pipes data from stdout as encoded bytes. We can run an external command or a program and get its output.
The syntax of check_output() is as follows
Example:
subprocess.check_output(args, *,stdin=None, stderr=None, shell=False, universal_newlines=False)
Output:
args is the shell command used.
The use of shell=True would be a security risk as per the Python documentation.
For Linux:
Example:
import subprocess subprocess.check_output('cp source_file.txt destination_.txt', shell=True)
Output:
For Windows:
Example:
import subprocess subprocess.check_output('copy source_file.txt destination_file.txt', shell=True)
Output: