Skip to main content
 首页 » 编程设计

python之从子进程开始时出现 EOFError

2024年12月31日9zhengyun_ustc

当我使用来自其他脚本的子进程启动我的 python3 脚本时,出现以下错误:

Select the keyword preset you want to use:Traceback (most recent call last): 
  File "test2.py", line 9, in <module> 
    keywordselect=input("Select the keyword preset you want to use:") 
EOFError 

但是当我使用 python3 generate.py 正常启动脚本时,它工作得很好,没有错误。

脚本1:

import subprocess 
p = subprocess.Popen(["python3", "test2.py"]) 

脚本2:

print("Keyword") 
print("1. Preset1") 
print("2. Preset2") 
print("3. Preset3") 
print("4. Preset4") 
print("You can edit the presets in /presets/keywords/.") 
selecting = 1 
while selecting == 1: 
    keywordselect=input("Select the keyword preset you want to use:") 
    if keywordselect == "1": 
        print("You selected keyword preset 1.") 
        selectedkeywordlist = "presets/keywords/preset1.txt" 
    elif keywordselect == "2": 
        print("You selected keyword preset 2.") 
        selectedkeywordlist = "presets/keywords/preset2.txt" 
    elif keywordselect == "3": 
        print("You selected keyword preset 3.") 
        selectedkeywordlist = "presets/keywords/preset3.txt" 
    elif keywordselect == "4": 
        print("You selected keyword preset 4.") 
        selectedkeywordlist = "presets/keywords/preset4.txt" 
    else: 
        print("You didn't select a valid option, please try again.") 

请您参考如下方法:

您正在使用 subprocess.Popen,默认情况下这是一段非阻塞的代码,因此您编写光标移动程序而不是等待用户输入。但是你需要的是一个代码来阻止你的程序光标。 subprocess.call 正是这样做的。它将等待其他命令完全执行。

您需要使用subprocess.call 来解决您的问题。只需更改您的 script2 文件即可

import subprocess 
p = subprocess.call(["python", "abca.py"]) 

您可以在 this answer 中阅读更多关于 subprocess.Popen 和 subprocess.call 之间区别的信息.其中描述了何时使用哪个命令以及它们之间的区别