“ int()参数必须是一个字符串”,来自int(p.returncode)和subprocess.Popen对象

问题描述 投票:0回答:1

我正在开发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编写命令似乎可行。

编辑:

我尝试了wait()并没有任何进展,但是有了run(),我得到了不同的输出:

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.run(
                tar_args,
                stdout=subprocess.PIPE,
                stdin=subprocess.PIPE,
                encoding='utf8'
            )
        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.run(
            remove_args,
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            encoding='utf8'
        )
    print("OK.")
    if int(process.returncode) != 0:
        print('Command failed. Return code : {}'.format(process.returncode))
except Exception as e:
    print(e)
    exit(1)

输出:

tar: Removing leading `/' from member names
tar: /xxx/xxx/xxx/11-04-2020/01\:12\:50: file changed as we read it
Command failed. Return code : 1

以及第二个块:

find: unknown predicate `-type f'
python-3.x bash subprocess tar
1个回答
0
投票

创建新的subprocess.Popen对象开始进程。它不会等待它完成,并且没有returncode存在未完成的过程。

等待Popen对象完成的历史方法是在其上调用wait()函数。您也可以改用subprocess.run或其他本身隐式等待完成的帮助程序,例如communicate()

© www.soinside.com 2019 - 2024. All rights reserved.