简体   繁体   English

Python 子进程 — 如何忽略退出代码警告?

[英]Python subprocess — how to ignore exit code warnings?

I am trying to display the final results.txt file via default program.我正在尝试通过默认程序显示最终的 results.txt 文件。 I've tried with bare Popen() without run() and got the same effect.我尝试使用没有run()的裸Popen() ) 并获得了相同的效果。 The target file is opening (for me it's the see mode) but after exiting it I receive:目标文件正在打开(对我来说是查看模式),但退出后我收到:

Warning: program returned non-zero exit code #256警告:程序返回非零退出代码 #256

Is there any way to ignore it and prevent my program from displaying such warning?有什么办法可以忽略它并阻止我的程序显示这样的警告? I don't care about it because it's the last thing the program does, so I don't want people to waste their time clicking Enter each time...我不关心它,因为它是程序做的最后一件事,所以我不希望人们每次都浪费时间点击 Enter ......

Code's below:代码如下:

from subprocess import run, Popen

if filepath[len(filepath)-1] != '/':
   try:
       results = run(Popen(['start', 'results.txt'], shell=True), stdout=None, shell=True, check=False)
   except TypeError:
        pass
else:
   try:
       results = run(Popen(['open', 'results.txt']), stdout=None, check=False)
   except TypeError:
       pass
   except FileNotFoundError:
       try:
           results = run(Popen(['see', 'results.txt']), stdout=None, check=False)
       except TypeError:
           pass
       except FileNotFoundError:
           pass

Your immediate error is that you are mixing subprocess.run with subprocess.Popen .您的直接错误是您将subprocess.runsubprocess.Popen混合在一起。 The correct syntax is正确的语法是

y = subprocess.Popen(['command', 'argument'])

or或者

x = subprocess.run(['command', 'argument'])

but you are incorrectly combining them into, effectively但是您错误地将它们有效地组合成

x = subprocess.run(subprocess.Popen(['command', 'argument']), shell=True)

where the shell=True is a separate bug in its own right (though it will weirdly work on Windows).其中shell=True本身就是一个单独的错误(尽管它会在 Windows 上奇怪地工作)。

What happens is that Popen runs successfully, but then you try to run run on the result, which of course is not a valid command at all.发生的情况是Popen成功运行,但是您尝试在结果上运行run ,这当然不是一个有效的命令。

You want to prefer subprocess.run() over subprocess.Popen in this scenario;在这种情况下,您希望subprocess.run()优于subprocess.Popen the latter is for hand-wiring your own low-level functionality in scenarios where run doesn't offer enough flexibility (such as when you require the subprocess to run in parallel with your Python program as an independent process).后者用于在run不能提供足够灵活性的情况下手动连接您自己的低级功能(例如,当您需要子进程与 Python 程序作为独立进程并行运行时)。

Your approach seems vaguely flawed for Unix-like systems;对于类 Unix 系统,您的方法似乎存在模糊的缺陷; you probably want to run xdg-open if it's available, otherwise the value of os.environ["PAGER"] if it's defined, else fall back to less , else try more .如果xdg-open可用,您可能想运行它,否则os.environ["PAGER"]的值(如果已定义),否则回退到less ,否则尝试more Some ancient systems also have a default pager called pg .一些古老的系统也有一个名为pg的默认寻呼机。

You will definitely want to add check=True to actually make sure your command fails properly if the command cannot be found, which is the diametrical opposite of what you appear to be asking.如果找不到命令,您肯定会想要添加check=True以实际确保您的命令正确失败,这与您所要求的截然相反。 With this keyword parameter, Python checks whether the command worked, and will raise an exception if not.使用这个关键字参数,Python 会检查命令是否有效,如果没有则抛出异常。 (In its absence, failures will be silently ignored, in general.) You should never catch every possible exception; (如果没有它,通常会默默地忽略失败。)您永远不应该捕获所有可能的异常; instead, trap just the one you really know how to handle.相反,只捕获你真正知道如何处理的那个。

Okay, I've achieved my goal with a different approach.好的,我用不同的方法实现了我的目标。 I didn't need to handle such exception, I did it without the subprocess module.我不需要处理这样的异常,我没有 subprocess 模块就做到了。

Question closed, here's the final code (it looks even better):问题结束,这是最终代码(看起来更好):

from os import system
from platform import system as sysname

if sysname() == 'Windows':
    system('start results.txt')
elif sysname() == 'Linux':
    system('see results.txt')
elif sysname() == 'Darwin':
    system('open results.txt')
else:
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM