$?返回值问题

FFFFFLK 发布于 02/10 14:19
阅读 113
收藏 0

环境描述:Python3.6

问题描述:我在脚本中执行了scp, scp成功后$?得到预期外的结果

test.sh代码

www.qipaike.com_【官方首页】-棋牌客#!/bin/bash
# localfile为本地真实存在文件, remote_host为真实存在服务器ip。ssh配置已经配置过,并且单独执行test.sh没有问题
scp -q localfile remote_host:~/ 2>&1
echo $?
exit 0

worker.py代码

import subprocess
from multiprocessing import Process
import os
import signal
import sys
from multiprocessing import set_start_method

def _detach_with_context(executor):
    os.setsid()

    signal.signal(signal.SIGCHLD, signal.SIG_IGN)

    pid = os.fork()
    if pid > 0:
        sys.exit(0)

    try:
        if pid < 0:
            sys.exit(0)

        executor()
    except Exception as ex:
        pass
    finally:
        sys.exit(0)


def detach_execute(executor):
    try:
        p = Process(target=_detach_with_context, args=(executor,))

        p.start()
        p.join()
    except Exception as ex:
        pass


def execute():
    command='sh ./test.sh'

    p = subprocess.Popen(
        command.encode('utf-8'),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True,
        encoding='UTF-8'
    )
    print("code={}".format(''.join(p.stdout.readlines())))


if __name__ == '__main__':
    set_start_method('spawn')
    detach_execute(execute)

单独执行test.sh,$?是0, 但是运行python3 worker.py $?就变成了1, scp -v查看过日志, 确认scp成功了。

为何$?值是1呢?

返回顶部
顶部

页面底部区域 foot.htm