账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    使用python调用外部程序产生进程,优雅关闭的最佳实践是什么?
    94
    0

    使用subprocess库:

    try:
        p = subprocess.Popen(["ping", "-c", "5", "www.bing.com"], stdout=subprocess.PIPE)
        p.wait()
    except KeyboardInterrupt as e:
        p.terminate()

    或者使用sh库:

    try:
        p = sh.ping("-c", "5", "www.bing.com", _bg=True, _bg_exc=False, 
                    _out=sys.stdout, _err=sys.stderr)
        p.wait()
    except KeyboardInterrupt as e:
        alive, _ = p.process.is_alive()
        if alive:
            p.process.terminate()

    这种结束外部进程的方式有什么缺点?

    1
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 寂寞的石头 普通会员 1楼

      在Python中调用外部程序并使进程优雅关闭的最佳实践是使用subprocess模块。subprocess模块提供了一个简单的方法来运行命令,获取其输出,并在完成操作后关闭它。

      以下是一个示例:

      ```python import subprocess

      def run_command(command): try: process = subprocess.Popen(command, shell=True) process.wait() print("Command executed successfully.") except subprocess.CalledProcessError as e: print("Error occurred while executing command: ", e)

      Call the command

      run_command("ls") ```

      在这个例子中,我们首先导入了subprocess模块。然后,我们定义了一个名为run_command的函数,该函数接受一个命令作为参数。在函数中,我们尝试使用subprocess.Popen函数来运行命令,并等待它完成。如果命令执行成功,我们将打印一条消息。如果在运行命令时发生任何错误,我们将捕获异常,并打印一条错误消息。

      最后,我们调用run_command函数,传入"ls"作为命令。

      这种方式可以使你的代码更加健壮,因为如果命令执行失败,你将能够捕获并处理错误。此外,它还使得代码更加清晰,因为你可以在函数中定义你的逻辑,而不是在代码的末尾添加更多的条件语句。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部