Partage
  • Partager sur Facebook
  • Partager sur Twitter

petit souci en python: IndentationError: unexpected unindent

dans une ligne qui n'esxiste pas !

Sujet résolu
    4 novembre 2011 à 15:13:19

    Bonjour amis Zéros

    Je tente en ce moment de faire un petit script simple qui permettrais de créer des fichiers contenant les lignes de base d'un script bash ou html, histoire de ne pas avoir à les retaper tout le temps et d'apprendre un peu python par la même occasion.
    Je n'en suis qu'au tout début et je rencontre déjà un soucis !
    Voici le code:

    #!/usr/local/bin/python3.2
    # -*-coding:utf-8 -*
    
    import sys
    import getopt
    
    ##fonctions
    def bash():
        print("bash")
        fichiersh = open("test.txt", "w")                                                                                    
        fichiersh.write("#!/bin/bash")
        fichiersh.close()
    
    
    def html():
        print("html")
        fichierhtml = open("test.html" , "a")
        fichierhtml.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
        fichierhtml.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
        fichierhtml.write('  <head>\n')
        fichierhtml.write('    <title>Testing PasteHTML.com</title>\n')
        fichierhtml.write('  </head>\n')
        fichierhtml.write('  <body>\n')
        fichierhtml.write('    <p>This is a test. Replace all this HTML with your own code.</p>\n')
        fichierhtml.write('  </body>\n')
        fichierhtml.write('</html>\n')
        fichierhtml.close()
    
    ##main
    def main(argv):
        try:
            opts, args = getopt.getopt(sys.argv, "bh")
    
            for opt, arg in opts:
                if opt in ("-b"):
                    print("==script bash==")
                    bash()
                elif opt in ("-h"):
                    print("==script html==")
                    html()
    


    Voici l'erreur:

    $> ./mkfsource.py 
      File "./mkfsource.py", line 42
        
        ^
    IndentationError: unexpected unindent


    J'ai surement fait pas mal de bêtises :( et je ne comprend pas pourquoi l’erreur se trouve dans une ligne qui n'existe pas :o !
    Merci d'avance pour vos lumières!

    ps: le code est plein d'approximation, c'est juste un essai pour l'instant !
    • Partager sur Facebook
    • Partager sur Twitter
      4 novembre 2011 à 16:02:38

      Merci je vais tester ça ...
      En Effet sur le tuto que j'ai suivis pour getopt (tuto) il y a bien cette ligne.
      Je vais bidouiller
      • Partager sur Facebook
      • Partager sur Twitter
      Anonyme
        4 novembre 2011 à 19:36:19

        Tu utilises Python 3 et le tuto cité parle de Python 2 alors si tu veux continuer avec Python 3, saches que la syntaxe des exceptions a légèrement changée : À la place de la virgule il faut utiliser le mot clé as.

        try:
            ...
        except Error as err:
            ...
        
        • Partager sur Facebook
        • Partager sur Twitter
          5 novembre 2011 à 0:00:27

          Merci pour vos réponses, c'est vrai que j'étais au fait des différences entres les versions de python mais que j'avais loupé celle ci.
          Ceci étant corrigé, aucune erreur n'apparait, je pense donc mettre le sujet en "résolut' malgré que les fonctions ne s'exécutent pas à l'appel de l'option :( ... Donc si vous avec un petit indice, n’hésitez pas.
          Merci encore
          • Partager sur Facebook
          • Partager sur Twitter
            5 novembre 2011 à 0:03:48

            Peut-être utiliser sys.argv[1:] pour éviter de prendre le nom de l'exécutable dans les options (et d'emmêler les pinceaux de getopt?). Sinon essaye de mettre des print dans le for, ça peut aider.
            • Partager sur Facebook
            • Partager sur Twitter
              5 novembre 2011 à 0:40:50

              En fait, je n'arrive pas trop à saisir le sens (le rôle) de sys.argv[1:]...

              voici ou j'en suis du code en m'aidant de la doc python 3.1.3

              #!/usr/local/bin/python3.2                                                                                                         
              # -*-coding:utf-8 -*
              
              import sys, getopt
              
              ##fonctions
              def bash():
                  print("bash")
                  fichiersh = open("test.txt", "w")
                  fichiersh.write("#!/bin/bash")
                  fichiersh.close()
              
              
              def html():
                  print("html")
                  fichierhtml = open("test.html" , "a")
                  fichierhtml.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
                  fichierhtml.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
                  fichierhtml.write('  <head>\n')
                  fichierhtml.write('    <title>Testing PasteHTML.com</title>\n')
                  fichierhtml.write('  </head>\n')
                  fichierhtml.write('  <body>\n')
                  fichierhtml.write('    <p>This is a test. Replace all this HTML with your own code.</p>\n')
                  fichierhtml.write('  </body>\n')
                  fichierhtml.write('</html>\n')
                  fichierhtml.close()
              
              def usage(): print("usage : ./mkfsource [option] [nomdufichier]")
              
              ##main
              def main():
                  try:
                      opts, args = getopt.getopt(sys.argv[1:], "ubh", ["usage"])
                  except getopt.GetoptError as err:
                      print(err)
                      usage()
                      exit(2)
              
                      for u, b, h, in opts:
                          if u in ("-u", "--usage"):
                              usage()
                          elif b =="-b":
                              print("==script bash==")
                              bash()
                          elif h == "-h":
                              print("==script html==")
                              html()
              
              if __name__ == '__main__': main()
              
              • Partager sur Facebook
              • Partager sur Twitter
                5 novembre 2011 à 0:51:01

                En mettant le for dans le try et en appelant la fonction main (if __name__ == '__main__': main() #toussa toussa?
                • Partager sur Facebook
                • Partager sur Twitter
                  5 novembre 2011 à 0:58:43

                  Cette ligne est bien présente, désolé je n'avais pas copier-coller cette ligne dans le poste, c'est corrigé...
                  • Partager sur Facebook
                  • Partager sur Twitter
                    5 novembre 2011 à 1:03:03

                    Le for dans le try (en gros comme dans ton premier post, et comme dis dans mon précédent post)...
                    • Partager sur Facebook
                    • Partager sur Twitter
                      5 novembre 2011 à 1:29:24

                      Je ne comprend pas très bien ce que tu entend par "mettre le for dans le try"

                      j'ai don testé ceci:

                      #!/usr/local/bin/python3.2                                                                                                                            
                      # -*-coding:utf-8 -*
                      
                      import sys
                      import getopt
                      
                      ##fonctions
                      def bash():
                          print("bash")
                          fichiersh = open("test.txt", "w")
                          fichiersh.write("#!/bin/bash")
                          fichiersh.close()
                      
                      
                      def html():
                          print("html")
                          fichierhtml = open("test.html" , "a")
                          fichierhtml.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
                          fichierhtml.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
                          fichierhtml.write('  <head>\n')
                          fichierhtml.write('    <title>Testing PasteHTML.com</title>\n')
                          fichierhtml.write('  </head>\n')
                          fichierhtml.write('  <body>\n')
                          fichierhtml.write('    <p>This is a test. Replace all this HTML with your own code.</p>\n')
                          fichierhtml.write('  </body>\n')
                          fichierhtml.write('</html>\n')
                          fichierhtml.close()
                      
                      def usage(): print("usage : ./mkfsource [option] [nomdufichier]")
                      
                      ##main
                      def main():
                          try:
                              opts, args = getopt.getopt(sys.argv[1:], "ubh", ["usage"])
                      
                              for u, b, h, in opts:
                                  if u in ("-u", "--usage"):
                                      usage()
                                  elif b =="-b":
                                      print("==script bash==")
                                      bash()
                                  elif h == "-h":
                                      print("==script html==")
                                  html()
                      
                          except getopt.GetoptError as err:
                              print(err)
                              usage()
                              exit(2)
                      
                      if __name__ == '__main__': main()
                      


                      Ce qui nous retourne :



                      ./mkfsource2.py -u
                      Traceback (most recent call last):
                        File "./mkfsource2.py", line 51, in <module>
                          if __name__ == '__main__': main()
                        File "./mkfsource2.py", line 36, in main
                          for u, b, h, in opts:
                      ValueError: need more than 2 values to unpack


                      J'ai donc changé
                      sys.argv[1:]
                      
                      en
                      sys.argv[2:]
                      
                      ce qui ne retourne absolument rien, aucune des fonctions ne semble être appelé :(
                      • Partager sur Facebook
                      • Partager sur Twitter
                        5 novembre 2011 à 1:35:48

                        ValueError: need more than 2 values to unpack

                        Ça veut dire que tu veux "unpacker" plus de 2 valeurs (u, b, h dans ton cas), alors que tu ne peux en "unpacker" que 2. C'est pour ça que j'ai dis le for du premier post, qui lui est bon.
                        • Partager sur Facebook
                        • Partager sur Twitter
                          5 novembre 2011 à 2:54:25

                          Problème réglé, et ça roule à merveille!
                          code final

                          import sys
                          import getopt
                          
                          def usage(): print("\n./mkfsource [option]")
                          
                          def bash():
                              print("bash")
                              fichiersh = open("test.sh", "w")
                              fichiersh.write("#!/bin/bash")
                              fichiersh.close()
                          
                          def html():
                              print("html")
                              fichierhtml = open("test.html" , "a")
                              fichierhtml.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n')
                              fichierhtml.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
                              fichierhtml.write('  <head>\n')
                              fichierhtml.write('    <title>Testing PasteHTML.com</title>\n')
                              fichierhtml.write('  </head>\n')
                              fichierhtml.write('  <body>\n')
                              fichierhtml.write('    <p>This is a test. Replace all this HTML with your own code.</p>\n')
                              fichierhtml.write('  </body>\n')
                              fichierhtml.write('</html>\n')
                              fichierhtml.close()
                          
                          try:
                              opts, args = getopt.getopt(sys.argv[1:], "hbu")
                          except getopt.GetoptError as err:
                              print(err)
                              usage()
                              sys.exit(2)
                          
                          for o, a in opts:
                              if o == "-b":                                                                                                                                     
                                  bash()
                              elif o in "-h":
                                  html()
                                  sys.exit()
                              elif o in "-u":
                                  usage()
                              else:
                                  print("Option {} inconnue".format(o))
                                  sys.exit(2)
                          


                          Merci cerium50 pour ton aide :)
                          bonne nuit
                          • Partager sur Facebook
                          • Partager sur Twitter

                          petit souci en python: IndentationError: unexpected unindent

                          × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                          × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                          • Editeur
                          • Markdown