Popen子进程异常 [英] Popen subprocess exception

查看:331
本文介绍了Popen子进程异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个简单的问题,并且之前已经回答过,但我在任何地方都找不到.

Sorry if this is a simple question and has been answered before, but I couldn't find it anywhere.

我正在尝试监听UDP数据包,如果它们是某些数据包,请运行不同的批处理脚本.我可以正常运行,但是我发现,如果Popen命令找不到该文件,它将触发异常,并且脚本停止运行.理想情况下,我希望它打印一条消息,然后继续侦听其他数据包并对其执行操作,仅向我们提供一条用于调试的消息.这是我使用的代码,我该怎么做?

I'm trying to listen to UDP packets and if they are certain packets, run different batch scripts. I have this working correctly, but I have found that if the Popen command doesn't find the file it triggers an exception and the script stops running. Ideally, I want this to print a message and then continue listening for other packets and act upon them, just giving us a message for debugging. Here is the code I have used, how could I do this?

if rxdata == "Camera 1":
    from subprocess import Popen
    try:
        p = Popen("Camera 1.bat", cwd=r"C:\xxx")
        stdout, stderr = p.communicate()
    except FileNotFoundError():
        print('Camera 1.bat not found')
elif rxdata == "Camera 2":
    from subprocess import Popen
    p = Popen("Camera 2.bat", cwd=r"C:\xxx")
    stdout, stderr = p.communicate()

在两个示例中,我都收到以下内容,并且脚本关闭.

In both examples, I receive the following and the script closes.

Traceback (most recent call last):
   File "C:\UDP Listener.py", line 42, in <module>
     p = Popen("Camera 1.bat", cwd=r"C:\xxx")
   File "C:\Python34\lib\subprocess.py", line 858, in __init__
     restore_signals, start_new_session)
   File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child
     startupinfo)
   FileNotFoundError: [WinError 2] The system cannot find the file specified

预先感谢

马特

推荐答案

奇怪的是,在我的PC上重新安装python之后,现在一切正常.不知道出了什么问题,但是当我现在运行代码并发现异常时,代码将按预期打印.

Strangely, after re-installing python on my PC everything is now working correctly. Not sure what went wrong but when I run the code now and an exception is found then the code prints as expected.

感谢您的帮助!

这篇关于Popen子进程异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆