cat*_*ode 87 python subprocess
我在命令行中做了什么:
cat file1 file2 file3 > myfile
Run Code Online (Sandbox Code Playgroud)
我想用python做什么:
import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
Run Code Online (Sandbox Code Playgroud)
Rya*_*son 237
要回答原始问题,要重定向输出,只需将参数的打开文件句柄传递stdout给subprocess.call:
# Use a list of args instead of a string
input_files = ['file1', 'file2', 'file3']
my_cmd = ['cat'] + input_files
with open('myfile', "w") as outfile:
subprocess.call(my_cmd, stdout=outfile)
Run Code Online (Sandbox Code Playgroud)
但正如其他人所指出的那样,cat为此目的使用外部命令是完全无关紧要的.
Mar*_*tos 20
更新:不鼓励使用os.system,尽管仍然可以在Python 3中使用.
用途os.system:
os.system(my_cmd)
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用子进程,这里的解决方案(主要是从子进程的文档中提取):
p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)
Run Code Online (Sandbox Code Playgroud)
OTOH,你可以完全避免系统调用:
import shutil
with open('myfile', 'w') as outfile:
for infile in ('file1', 'file2', 'file3'):
shutil.copyfileobj(open(infile), outfile)
Run Code Online (Sandbox Code Playgroud)
@PoltoS 我想加入一些文件,然后处理生成的文件。我认为使用 cat 是最简单的选择。有没有更好的/pythonic方法来做到这一点?
当然:
with open('myfile', 'w') as outfile:
for infilename in ['file1', 'file2', 'file3']:
with open(infilename) as infile:
outfile.write(infile.read())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80294 次 |
| 最近记录: |