在subprocess.call中使用大于运算符 [英] Using greater than operator with subprocess.call

查看:54
本文介绍了在subprocess.call中使用大于运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的很简单。我想使用python的子进程模块调用以下命令。

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

该命令简单起作用并复制 file_A 到当前工作目录中的 file_B 。但是,当我尝试在脚本中使用 subprocess 模块调用此命令时,会出错。以下是我在做什么:

The command simply works and copies the contents of file_A to file_B in current working directory. However when I try to call this command using the subprocess module in a script it errors out. Following is what I am doing:

import subprocess

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

出现以下错误:

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

我做错了吗?如何在子流程模块 call 命令中使用大于运算符?

what am I doing wrong ? How can I use the greater than operator with subprocess modules call command ?

推荐答案

> 输出重定向是 shell 功能,但是 subprocess.call()带有 args 列表并且 shell = False (默认)的列表不使用shell。

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

您必须在此处使用 shell = True

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

或更妙的是,使用 subprocess 将命令的输出重定向到文件:

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)

如果只是复制文件,请使用 shutil.copyfile()函数具有 Python 复制文件acros s:

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')

这篇关于在subprocess.call中使用大于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆