Using the statement more with subprocess.call

What I'm trying to do is pretty simple. I want to call the following command using the python module subprocess.

cat /path/to/file_A > file_B

The command just works and copies the contents file_Ato file_Bthe current working directory. However, when I try to call this command using a module subprocessin a script, this leads to errors. That's what I'm doing:

import subprocess

subprocess.call(["cat", "/path/to/file_A", ">", "file_B"])

and I get the following error:

cat: /path/to/file_A: No such file or directory
cat: >: No such file or directory
cat: file_B: No such file or directory

what am I doing wrong? How can I use an operator more than an operator with subprocess modules call?

+4
source share
2 answers

> - , subprocess.call() args shell=False ( ) .

shell=True :

subprocess.call("cat /path/to/file_A > file_B", shell=True)

, subprocess :

with open('file_B', 'w') as outfile:
    subprocess.call(["cat", "/path/to/file_A"], stdout=outfile)

, shutil.copyfile() , Python :

import shutil

shutil.copyfile('/path/to/file_A', 'file_B')
+8

Martijn:

, cat :

with open("/path/to/file_A") as file_A:
    a_content = file_A.read()
with open("file_B", "w") as file_B:
    file_B.write(a_content)
0

All Articles