使子进程调用使用生成的文件名

2 python subprocess

所以我有一个python脚本,根据时间生成一个文件名.然后我尝试将cat一些数据写入该文件名.但是,似乎我无法传递它或其他东西.

这是代码的样子:

fileName = "parsedOn_"+strftime("%Y_%m_%d_%H%M%S", gmtime())+".csv"
subprocess.call(['cat' + 'xaa' + '>' + fileName])
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

Traceback (most recent call last):
File "parseCSV.py", line 96, in <module>
subprocess.call(['cat' + 'xaa' + '>' + finalFile1])
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 1106, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Run Code Online (Sandbox Code Playgroud)

任何想法,如果我正在尝试做什么是可能的子进程?

phi*_*hag 6

问题在于

subprocess.call(['cat' + 'xaa' + '>' + fileName])
Run Code Online (Sandbox Code Playgroud)

首先,您缺少空格(如果您想使用字符串)或逗号(如果您想使用列表,则首选方法).其次,>是一个shell重定向,所以你必须在shell中执行这一行,如:

subprocess.call('cat xaa > ' + fileName, shell=True)
Run Code Online (Sandbox Code Playgroud)

但你不应该这样做.相反,使用Python的原生shutil.copyfile:

shutil.copyfile('xaa', fileName)
Run Code Online (Sandbox Code Playgroud)