subprocess.Popen和communic()不执行程序,而终端执行

问题描述 投票:0回答:1

我有一个例程,我每天早上跑,我想要一系列的程序运行。它看起来像这样。 (programCaller.py的内容)

programs = [
    'program 1',
    'program 2',
    'program 3'
    ]

for program in programs:
    print('Executing: ' + program)
    p = subprocess.Popen('/path/to/directory/' + program)
    p.communicate()

一周前,一切都很好。它实时通信(我在Windows上努力获得的振作,因为我在Mac上运行它),如果一个程序失败,它将进入下一个程序。

现在它不只是从IDLE运行。但是,从终端“./programCaller.py”可以正常工作。

所有课程都有shebang系列和课程许可。我已经尝试了shell = True,可执行文件,stdout和其他参数的所有变体,但它不起作用。

它的作用是它立即完成执行,给我“>>>”提示,就像它完成了一样。它不是在后台工作,因为我测试了一个非常简单的程序,它给我发了一封邮件,而且它没有这样做。

某些东西必须已经改变,也许它使用另一个可执行文件,但它是一个无声的崩溃。

python terminal subprocess popen execution
1个回答
0
投票

如果它是一个启动调用,你应该确保用你想要的python正确调用programCaller.py所以"/path/to/Python/python" programCaller.py我不知道它如何适用于Mac但在Windows上我建议你使用https://pypi.org/project/auto-py-to-exe/创建一个基于programCaller.py的exe。

此外,如果你想进行调试,可以在time.sleep()之后添加一个print(p)p.communicate(),以确保正确创建子进程。我建议这样做,因为如果你有不同版本的Python,你可能会遗漏一些外部库。

更复杂的东西是:

try:
    p = subprocess.Popen('/path/to/directory/' + program)
    stdout, stderr = p.communicate()
    print(stdout)
    print(stderr)
except KeyboardInterrupt:
    p.kill()
    print("KeyboardInterrupt: killing process")
except Exception as e:
    print(e)

如果子进程不需要输入:

try:
    p = subprocess.Popen('/path/to/directory/' + program)
    output = p.stdout.readline()
    if output:
        sys.stdout.flush()
        print(output)
except KeyboardInterrupt:
    p.kill()
    print("KeyboardInterrupt: killing process")
except Exception as e:
    print(e)
© www.soinside.com 2019 - 2024. All rights reserved.