【问题标题】:I think my computer has built in python 2 and I installed python 3我想我的电脑已经内置了 python 2,我安装了 python 3
【发布时间】:2015-07-29 05:51:10
【问题描述】:

我的电脑上运行着 windows 8,我想我同时下载了 python 2 和 3,或者我认为我的电脑内置了 python 2,我下载了 python 3。现在当我在 IDLE 中运行我的代码时,代码可以工作很好,但是当我保存我的程序并双击保存文件时,它会运行,但它不像以前在 IDLE 中那样工作。

有人可以解释我目前面临的可能问题吗?

我只想让我的程序在 IDLE 和双击保存的文件时都能完美运行。

我尝试了 Anand S. Kumar 的建议,但我不确定自己在做什么。

所以这是我在 CMD 管理员中输入的内容,但输出仍然与上面的第一张图片相同。

这里是代码

游戏模块:

# Games
# Demonstrates module creation

class Player(object):
    """ A player for a game. """
    def __init__(self, name, score = 0):
        self.name = name
        self.score = score

    def __str__(self):
        rep = self.name + ":\t" + str(self.score)
        return rep

def ask_yes_no(question):
    """Ask a yes or no question."""
    response = None
    while response not in("y", "n"):
        response = input(question).lower()
    return response

def ask_number(question, low, high):
    """Ask for a number within a range."""
    response = None
    while response not in range(low, high):
        response = int(input(question))
    return response

if __name__ == "__main__":
    print("You ran this module directly (and did not 'import' it).")
    input("\n\nPress the enter key to exit.")

卡片模块:

# Cards Module
# Basic classes for a game with playing cards

class Card(object):
    """ A playing card. """
    RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
    SUITS = ["c", "d", "h", "s"]

    def __init__(self, rank, suit, face_up = True):
        self.rank = rank
        self.suit = suit
        self.is_face_up = face_up

    def __str__(self):
        if self.is_face_up:
            rep = self.rank + self.suit
        else:
            rep = "XX"
        return rep

    def flip(self):
        self.is_face_up = not self.is_face_up

class Hand(object):
    """A hand of playing cards."""
    def __init__(self):
        self.cards = []

    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep += str(card) +  "\t"
        else:
            rep = "<empty>"
        return rep

    def clear(self):
        self.cards = []

    def add(self, card):
        self.cards.append(card)

    def give(self, card, other_hand):
        self.cards.remove(card)
        other_hand.add(card)

class Deck(Hand):
    """ A deck of playing card. """
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank, suit))

    def shuffle(self):
        import random
        random.shuffle(self.cards)

    def deal(self, hands, per_hand = 1):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.give(top_card, hand)
                else:
                    print("Can't continue deal. Out of cards!")

if __name__ == "__main__":
    print("This is a module with classes for playing cards.")
    input("\n\nPress the enter key to exit.")

然后是主要代码:

# Blackjack
# From 1 to 7 players compete against a dealer

# Daghan pakog wa nasabtan ani so balikan pa nako ni!

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1 # unsaon pag kabalo sa self.rank xia.
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit)) # kay naa may __init__ sa BJ_Card



class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards: 
            if not card.value:
                return None

        # add up card values, treat each ACE as 1
        t= 0
        for card in self.cards:
            t += card.value #-->? tungod sa @ property pwede na xa .value ra
                            #--> Libog  ning diri dapita, unsaon pag kabalo nga self.rank xia


        # determine if hand contains an ACE
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10

        return t

    def is_busted(self):
        return self.total > 21

class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """
    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ")
        return response == "y"

    def bust(self):
        print(self.name, "busts.")
        self.lose()

    def lose(self):
        print(self.name, "losses.")

    def win(self):
        print(self.name, "wins.")

    def push(self):
        print(self.name, "pushes.")

class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand =2)
        self.dealer.flip_first_card()   # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to playeres
        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()   # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)

        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

    # remove everyone's cards
        for player in self.players: # dapat inside ra xia sa class kay kung dili. self is not defined.
            player.clear()
        self.dealer.clear()

def main():
    print("\t\tWelcome to Blackjack!\n")

    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)

    print()

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play()
        again = games.ask_yes_no("\nDo you want to play again?: ")

main()
input("\n\nPress the enter key to exit.")

如果您不明白,请不要介意 cmets。顺便说一句,那是我的第一语言。

【问题讨论】:

  • 你是如何安装 python 3 的?
  • 你为什么不在这里分享你的代码?
  • 现在你的声誉是 10 张贴图片:)
  • 这可能是文件关联。 Windows 不读取#! 行,shell 必须在注册表中查找文件扩展名。可能是您使用了与 .py 关联的错误 python。几种解决方案,但首先在命令行中输入python -V,以及assoc 和ftype 命令,看看是否是问题所在。
  • 您需要使用elevated prompt 来运行发布的命令。

标签: python


【解决方案1】:

很可能,与.py 文件关联的默认程序是 Python 2.x 的可执行文件。这可能是您双击 python 文件时无法正常运行的原因。

因为当您双击一个文件(或在命令提示符下运行它而不提供可执行文件)时,Windows 会选择与 .py 文件关联的默认程序并使用该可执行文件运行该文件。

在您的情况下,即使您安装了 Python 3,这可能仍指向 Python 2。

从 python installation doc,要更改 Python 文件的默认可执行文件,请使用 -

您还可以使用 pythonw.exe 使所有 .py 脚本执行,设置 这通过通常的设施,例如(可能需要 管理权限):

  1. 启动命令提示符。

  2. 将正确的文件组与 .py 脚本相关联:

    assoc .py=Python.File 
    
  3. 将所有 Python 文件重定向到新的可执行文件:

    ftype Python.File=C:\Path\to\python3.exe "%1" %*
    

使用上述方法将 .py 文件重定向到 Python 3。

【讨论】:

  • 我试过了,先生,输出是我的问题的编辑版本,我做错了什么先生?我最近安装了一个新版本的python Python 3.4来解决这个问题,安装时我没有选择默认但我更改了默认安装过程并更改了路径。
  • 使用选项Run as administrator 运行命令提示符,然后试一试。请注意答案中的部分 - (might require administrative rights)。
  • 所以我按照您的回答先生并以管理员身份运行 cmd 但输出仍然相同
  • @JohnCruz 你确定你用管理员选项运行cmd 吗?您使用的用户是否没有这些权限?
  • 是的,我使用管理员选项运行它,我已经在上面编辑了我的问题。对吗?
【解决方案2】:

我从未尝试通过双击保存文件来运行 Python 程序,但我可以为您指明方向,告诉您如何在命令行或 Python Shell 中运行程序。

首先,Windows 不附带 Python 2 或 3。您只需转到 Python 文件的安装位置即可检查您拥有的版本。默认情况下,它们将位于 C 驱动器中。设置好环境路径后,您还可以通过 Python shell 检查您拥有的 Python 版本。

Here 是您可以找到设置环境以从命令行运行 Python 的步骤的地方。 This 也将帮助您设置环境。本质上,当您在命令行中键入“python”时,您正在做的是告诉 Windows 在哪里可以找到 Python 库。设置好环境后,您可以在命令行或 Python Shell 中运行文件。查看Escualo's 的答案,了解如何执行此操作。

【讨论】:

    【解决方案3】:

    您可以尝试将关联更改为:

    python.file="C:\Windows\py.exe" "%L" %*
    

    或将“C:\Windows”部分设置为 Python3.exe 所在的位置。

    Python 安装程序(至少对于 Python3)似乎指定文件名应该是宽字符形式;因此 %L 修饰符。

    顺便说一句。 你也可以在你的 cmd-shell 中使用 ftype (而不是四处寻找 在资源管理器中)。未经测试,请注意:

       ftype python.file=="C:\Windows\py.exe" "%L" %*
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-17
      • 2020-02-06
      • 1970-01-01
      • 2020-03-15
      • 2019-06-07
      • 2012-03-29
      • 1970-01-01
      • 2019-08-24
      相关资源
      最近更新 更多