"int() argument must be a string" 来自 int(p.returncode) 和 subprocess.Popen 对象

"int() argument must be a string" from int(p.returncode) with subprocess.Popen object

我正在开发一个 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.Popen 对象 启动 进程。它不会等待它完成,并且没有 returncode 存在未完成的进程。

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