Using greater than operator with subprocess.call

后端 未结 2 1278
小鲜肉
小鲜肉 2020-12-03 21:48

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

cat /path/to/file_A > file_B         


        
相关标签:
2条回答
  • 2020-12-03 22:35

    > output redirection is a shell feature, but subprocess.call() with an args list and shell=False (the default) does not use a shell.

    You'll have to use shell=True here:

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

    or better still, use subprocess to redirect the output of a command to a file:

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

    If you are simply copying a file, use the shutil.copyfile() function to have Python copy the file across:

    import shutil
    
    shutil.copyfile('/path/to/file_A', 'file_B')
    
    0 讨论(0)
  • 2020-12-03 22:48

    Addition to Martijn's answer:

    you can do the same thing as cat yourself:

    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 讨论(0)
提交回复
热议问题