【发布时间】:2020-04-10 20:37:31
【问题描述】:
我正在开发一个 Python 3 程序,通过 rsync 远程文件夹备份到本地 NAS。
我完美地同步了文件夹,但是当我想通过 .tar.gz 将文件夹压缩成一个文件时,我收到了这个错误:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
tar: Removing leading `/' from member names
file changed as we read it
tar: write error
生成压缩文件的函数是这个:
def make_tarfile(self, output_filename, source_dir):
try:
# Generate .tar.gz
print("Generating .tar.gz backup")
tar_args = ['tar', '-cvzf', source_dir+output_filename+'.tar.gz', source_dir]
process = subprocess.Popen(
tar_args,
stdout=subprocess.PIPE
)
if int(process.returncode) != 0:
print('Command failed. Return code : {}'.format(process.returncode))
print("OK.")
# Remove files
print("Removing files previously compressed.")
remove_args = ['find', source_dir, '-type f', '!', '-name "*.?*"', '-delete']
process = subprocess.Popen(
remove_args,
stdout=subprocess.PIPE
)
print("OK.")
if int(process.returncode) != 0:
print('Command failed. Return code : {}'.format(process.returncode))
except Exception as e:
print(e)
exit(1)
如果我用 bash 编写命令似乎可以工作。
【问题讨论】:
-
使用
subprocess.run而不是subprocess.Popen。它等待命令完成。 -
process.returncode在软件完成运行之前不会设置。 -
在您的问题以最初提出的正确方式得到回答后,以使现有答案无效的方式进行编辑是不道德的。遇到新问题时提出新问题。
-
也就是说,
'-type f'必须是'-type', 'f' -
同样,
'-name "*.?*"'应该是'-name', '*.?*'
标签: python-3.x bash subprocess tar