Python代码未在可执行文件中执行所有代码行。

huangapple go评论70阅读模式
英文:

python code does not execute all lines of code in exe file

问题

I have used pyinstaller to convert it but the code does not execute all my lines code in the exe file and cmd, but to notice is the original lines code are running perfectly in vs code

我已经使用pyinstaller来转换它,但该代码在exe文件和cmd中无法执行我的所有代码行,但值得注意的是原始代码在vs code中运行得很好。

I tried py installer also another named "auto py to exe"
我尝试了py installer还有另一个名为"auto py to exe"

The only thing I want to make the code run in user's windows
我唯一想要的是让代码在用户的Windows上运行

英文:

I have used pyinstaller to convert it but the code does not execute all my lines code in the exe file and cmd , but to notice is the original lines code are running perfectly in vs code

i tried py installer also another named "auto py to exe "
the only thing I want to make the code run in user's windows

import datetime

from dateutil.relativedelta import relativedelta

print("Welcome to the Recharge Assistant")

# Get today's date
today = datetime.date.today()

# Get the same day next year
same_day_next_year = datetime.date(today.year + 1, today.month, today.day)

# Get a valid date from the user
while True:
    user_input = input("Please enter your current validity (DD/MM/YYYY), or 'q' to quit: ")

    # Check if user wants to quit
    if user_input.lower() == 'q':
        break

    try:
        # Convert user's input to a date object
        user_date = datetime.datetime.strptime(user_input, "%d/%m/%Y").date()

        # Check if user's input is in the past or exceeds the same day next year
        if user_date < today:
            user_date = today
        elif user_date > same_day_next_year:
            user_date = same_day_next_year

        # Calculate the number of days between user_date and same_day_next_year
        DAYS_DIFF = (same_day_next_year - user_date).days
        if DAYS_DIFF == 0:
            print("You may have entered a wrong year or date!")

        # Handle leap year
        if DAYS_DIFF == 366:
            DAYS_DIFF = 365

        # Calculate the number of months and days in days_diff
        months = DAYS_DIFF // 30
        days = DAYS_DIFF % 30

        # Print the updated user date
        print("Current user Validity:", user_date)
        print("Max number of days that can be recharged until next year:", DAYS_DIFF)
        print(f"Number of months that can be recharged: {months} months and {days} days")

        while True:
            try:
                get_month = int(input("How many months do you need? "))
                get_days = get_month * 30
                new_date = user_date + relativedelta(months=get_month)
                print(f"You entered {get_month} months which is {get_days} days.")
                print("The resulting date will be:", new_date)
                break
            except ValueError:
                print("Invalid input. Please enter a valid integer.")

    except ValueError:
        print("Invalid date format. Please enter a valid date in the format DD/MM/YYYY.")

    # Add a break statement if the user entered a valid date to allow for quitting
    if user_input.lower() != 'q':
        break

答案1

得分: 1

从未遇到过这个问题,但你应该尝试重新安装Py,并检查是否缺少可能引起此错误的依赖项。

我建议运行 $ pip check,即使你是否在使用它,也要检查你的Conda环境。

我研究了你的情况,听说你可以尝试关闭控制台,或者将控制台设置为 false

英文:

Never had this problem before, but you should try reinstalling Py and Check if you have missing dependencies that can cause this error.

I suggest $ pip check and even if youre using it or not check your Conda eviroment.

I study your case and hear about you can try to shutdown the console or either set console ==true to false

答案2

得分: 1

经过再次查看,我意识到问题不是可执行文件的创建,而是异常处理的方式。我认为最好让您具体考虑在哪些行上您希望捕获异常。在这里,我将user_date = datetime.datetime.strptime(user_input, "%d/%m/%Y").date()这一行用try-except块单独包装起来,以便其他地方捕获的异常不会影响到这里。我还添加了一个continue关键字,使其在循环内继续执行。程序在完成后将立即关闭,因此您可以删除最后的if语句,让用户使用"q"作为输入来退出,或者添加一个sleep语句,以便用户有时间查看他们的结果。
我使用pyinstaller filename.py --onefile构建了这个程序,经过测试,现在应该可以正常工作。

import datetime
from dateutil.relativedelta import relativedelta

print("欢迎使用充值助手")

# 获取今天的日期
today = datetime.date.today()

# 获取明年的同一天
same_day_next_year = datetime.date(today.year + 1, today.month, today.day)

# 从用户那里获取有效日期
while True:
    user_input = input("请输入您当前的有效期(DD/MM/YYYY),或输入'q'退出:")

    # 检查用户是否想要退出
    if user_input.lower() == 'q':
        break

    try:
        # 将用户输入转换为日期对象
        user_date = datetime.datetime.strptime(user_input, "%d/%m/%Y").date()
    except ValueError:
        print("日期格式无效。请输入格式为DD/MM/YYYY的有效日期。")
        continue

    # 检查用户输入是否在过去或超过明年的同一天
    if user_date < today:
        user_date = today
    elif user_date > same_day_next_year:
        user_date = same_day_next_year

    # 计算user_date和明年同一天之间的天数差异
    DAYS_DIFF = (same_day_next_year - user_date).days
    if DAYS_DIFF == 0:
        print("您可能输入了错误的年份或日期!")

    # 处理闰年
    if DAYS_DIFF == 366:
        DAYS_DIFF = 365

    # 计算days_diff中的月数和天数
    months = DAYS_DIFF // 30
    days = DAYS_DIFF % 30

    # 打印更新后的用户日期
    print("当前用户有效期:", user_date)
    print("直到明年最多可以充值的天数:", DAYS_DIFF)
    print(f"可以充值的月数:{months}个月{days}天")

    while True:
        try:
            get_month = int(input("您需要多少个月?"))
            get_days = get_month * 30
            new_date = user_date + relativedelta(months=get_month)
            print(f"您输入了{get_month}个月,即{get_days}天。")
            print("结果日期将为:", new_date)
            break
        except ValueError:
            print("无效输入。请输入有效的整数。")
英文:

After taking another look at this I realized that the problem wasn't the creation of the executable but it was instead how the exceptions were handled. I think that is would be better for you to consider specifically what lines you are expecting to capture an exception at. Here I wrapped the line user_date = datetime.datetime.strptime(user_input, &quot;%d/%m/%Y&quot;).date() with the try-except block on its own, so other exceptions being caught elsewhere would not cause this to capture them. I also added a continue keyword to make it continue inside the loop. The program will close immediately when finished, so you should either remove the last if-statement and have the user quit out with "q" as an input, or add a sleep statement to give the user time to see their results.
I built this with pyinstaller filename.py --onefile tested it, and it should be working now.

import datetime
from dateutil.relativedelta import relativedelta
print(&quot;Welcome to the Recharge Assistant&quot;)
# Get today&#39;s date
today = datetime.date.today()
# Get the same day next year
same_day_next_year = datetime.date(today.year + 1, today.month, today.day)
# Get a valid date from the user
while True:
user_input = input(&quot;Please enter your current validity (DD/MM/YYYY), or &#39;q&#39; to quit: &quot;)
# Check if user wants to quit
if user_input.lower() == &#39;q&#39;:
break
try:
# Convert user&#39;s input to a date object
user_date = datetime.datetime.strptime(user_input, &quot;%d/%m/%Y&quot;).date()
except ValueError:
print(&quot;Invalid date format. Please enter a valid date in the format DD/MM/YYYY.&quot;)
continue
# Check if user&#39;s input is in the past or exceeds the same day next year
if user_date &lt; today:
user_date = today
elif user_date &gt; same_day_next_year:
user_date = same_day_next_year
# Calculate the number of days between user_date and same_day_next_year
DAYS_DIFF = (same_day_next_year - user_date).days
if DAYS_DIFF == 0:
print(&quot;You may have entered a wrong year or date!&quot;)
# Handle leap year
if DAYS_DIFF == 366:
DAYS_DIFF = 365
# Calculate the number of months and days in days_diff
months = DAYS_DIFF // 30
days = DAYS_DIFF % 30
# Print the updated user date
print(&quot;Current user Validity:&quot;, user_date)
print(&quot;Max number of days that can be recharged until next year:&quot;, DAYS_DIFF)
print(f&quot;Number of months that can be recharged: {months} months and {days} days&quot;)
while True:
try:
get_month = int(input(&quot;How many months do you need? &quot;))
get_days = get_month * 30
new_date = user_date + relativedelta(months=get_month)
print(f&quot;You entered {get_month} months which is {get_days} days.&quot;)
print(&quot;The resulting date will be:&quot;, new_date)
break
except ValueError:
print(&quot;Invalid input. Please enter a valid integer.&quot;)

huangapple
  • 本文由 发表于 2023年6月8日 01:47:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定