Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

May should merge run_cmd and exec_cmd to one. #22

Closed
zlj-zz opened this issue Apr 9, 2022 · 0 comments
Closed

May should merge run_cmd and exec_cmd to one. #22

zlj-zz opened this issue Apr 9, 2022 · 0 comments
Labels
enhance New feature or request

Comments

@zlj-zz
Copy link
Owner

zlj-zz commented Apr 9, 2022

def run_cmd(*args, cwd: Optional[str] = None) -> bool:
    """Run system command.

    Returns:
        (bool): Whether run successful.

    Docs test
        >>> run_cmd('pwd')
        True
        >>> run_cmd('which', 'python')
        True
    """

    try:
        # ? In python2, `subprocess` not support `with` sentence.
        proc = subprocess.Popen(" ".join(args), shell=True, cwd=cwd)
        proc.wait()
    except Exception:
        Log.error(traceback_info())
        return False
    else:
        return True


def exec_cmd(*args, cwd: Optional[str] = None) -> Tuple[str, str]:
    """Run system command and get result.

    Returns:
        (str, str): Error string and result string.
    """

    try:
        # Take over the input stream and get the return information.
        with subprocess.Popen(
            " ".join(args),
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE,
            shell=True,
            cwd=cwd,
        ) as proc:

            output = proc.communicate()
            # Get normal output and error output.
            res = output[0].decode()
            err = output[1].decode()
    except Exception as e:
        Log.error(traceback_info())
        return str(e), ""
    else:
        return err, res

Can use one parameter to contrl whether return result or ouput to shell.

@zlj-zz zlj-zz added the enhance New feature or request label Apr 9, 2022
@zlj-zz zlj-zz closed this as completed in 92426cc Apr 9, 2022
zlj-zz added a commit that referenced this issue Apr 9, 2022
(feat): merge `run_cmd` to `exec_cmd`. close #22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhance New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant