Passed
Push — master ( 652770...4381c0 )
by Erik
01:16
created

pypen/__main__.py (1 issue)

1
import sys
2
import argparse
3
import time
4
from os import path, getcwd
5
from importlib import util as import_util
6
import pkg_resources
7
8
from pypen.settings import settings
9
from pypen.drawing.pypen_window import PyPenWindow
10
11
import pyglet
12
13
_argument_parser = argparse.ArgumentParser()
14
15
def space_print(msg=""):
16
    print()
17
    print(msg)
18
    print()
19
20
def print_help(msg=""):
21
    global _argument_parser
22
    if msg:
23
        space_print(msg)
24
25
    _argument_parser.print_help(sys.stderr)
26
    sys.exit(0)
27
28
def cli():
29
    global _argument_parser
30
    try:
31
        _argument_parser = argparse.ArgumentParser(description="The PyPen CLI for managing PyPen Sketches", prog="pypen")
32
        _argument_parser.add_argument(
33
            "-i",
34
            "--init",
35
            action="store_true",
36
            help="Flag to create a new PyPen sketch which imports pypen and contains default functions.")
37
38
        _argument_parser.add_argument("filename", nargs="?", help="The name/path of your PyPen Sketch.", default="")
39
        _argument_parser.add_argument("-f", "--fullscreen", action="store_true")
40
        _argument_parser.add_argument(
41
            "--timeout",
42
            help="Timeout in milliseconds. Window will automatically close after this timeout.",
43
            type=float,
44
            required=False,
45
            default=0.0)
46
        _argument_parser.add_argument("-v", "--version",
47
                                      help="Displays the currently installed PyPen's version.",
48
                                      action="version",
49
                                      version=pkg_resources.get_distribution("pypen").version)
50
51
        arguments = _argument_parser.parse_args()
52
53
        if len(sys.argv) == 1:
54
            print_help("It seems like you are running the pypen command without any arguments.\nHere is some help:")
55
56
        if not arguments.init and not arguments.filename:
57
            print_help("PyPen needs a path to a sketch in order to run it!\nPlease provide a path with 'pypen <path_to_sketch>'\nor run 'pypen --init <path_to_new_sketch>' to create a new one!")
58
59
        if arguments.init:
60
            path_to_new_sketch = arguments.filename if arguments.filename else settings.default_pypen_name
61
            init(path_to_new_sketch)
62
63
        if path.splitext(arguments.filename)[1] != ".py":
64
            arguments.filename = "{}.py".format(arguments.filename)
65
66
        main(arguments)
67
    except argparse.ArgumentError as error:
68
        print(str(error))
69
        sys.exit(1)
70
71
72
def init(path_to_new_file):
73
    if path.splitext(path_to_new_file)[1] != ".py":
74
        path_to_new_file += ".py"
75
76
    pypen_path = path.join(getcwd(), path_to_new_file)
77
    template = ""
78
79
    try:
80
        with open(path.join(path.realpath(__file__), "..", "pypen_template.py"), "r") as template_file:
81
            template = template_file.read()
82
    except EnvironmentError:
83
        # In case PyPen is installed in a directory that doesn't have read access,
84
        # it uses the below template instead of reading the template file
85
        template = """from pypen import *
86
87
88
def start():
89
    settings.fps = 60
90
91
92
def update():
93
    fill_screen("orange")
94
    rectangle(20, 20, 300, 400, "red")
95
"""
96
97
    try:
98
        with open(pypen_path, "w") as new_file:
99
            new_file.writelines(template)
100
    except EnvironmentError:
101
        space_print("Could not create file {}\nDo you have the right permissions?".format(pypen_path))
102
        sys.exit(1)
103
104
    space_print("'{0}' has been created!\nRun it using 'pypen {0}'".format(path_to_new_file))
105
    sys.exit(0)
106
107
108
def main(arguments):
109
    if not arguments.init:
110
        try:
111
            file_path = path.join(getcwd(), arguments.filename)
112
            spec = import_util.spec_from_file_location("", file_path)
113
            user_sketch = import_util.module_from_spec(spec)
114
            spec.loader.exec_module(user_sketch)
115
        except FileNotFoundError:
116
            print()
117
            print(f"Hmm, PyPen can't find '{arguments.filename}'.")
118
            print("Are you sure that's the right path?")
119
            print()
120
            sys.exit(1)
121
122
    try:
123
        user_sketch.TIME
0 ignored issues
show
The variable user_sketch does not seem to be defined in case BooleanNotNode on line 109 is False. Are you sure this can never be the case?
Loading history...
124
        user_sketch.T
125
        user_sketch.PI
126
    except AttributeError as error:
127
        print()
128
        print(f"It seems like you're not importing PyPen to your sketch '{arguments.filename}'")
129
        print("Import it by writing 'from pypen import *' at the very top!")
130
        print()
131
132
        print(error)
133
        sys.exit(1)
134
135
    try:
136
        user_sketch.start
137
    except AttributeError:
138
        user_sketch.settings._user_has_start = False
139
140
    try:
141
        user_sketch.update
142
    except AttributeError:
143
        user_sketch.settings._user_has_update = False
144
145
    if not user_sketch.settings._user_has_start and not user_sketch.settings._user_has_update:
146
        print()
147
        print(f"Your PyPen sketch '{arguments.filename}' appears to have neither a start() nor an update() function.")
148
        print("Try to add at least one of those and run again!")
149
        print()
150
        sys.exit(1)
151
152
    window_title = f"PyPen | {path.splitext(path.split(arguments.filename)[1])[0]}"
153
    pypen_window = PyPenWindow(user_sketch, window_title, arguments)
154
155
    pyglet.app.run()
156
157
158
if __name__ == "__main__":
159
    cli()
160