Форум программистов, компьютерный форум, киберфорум
Python
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.69/13: Рейтинг темы: голосов - 13, средняя оценка - 4.69
0 / 0 / 1
Регистрация: 01.11.2012
Сообщений: 56

Как правильно открывать и читать файлы?

17.11.2013, 13:37. Показов 2794. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте, не пойму из-за чего начала вылетать следующая ошибка при вызове скрипта:
Вызываю так:
Python
1
python3 /home/cp/gameservers.py -action start -sid 1 -game cs -ip xx.xx.xx.xx -port 27015 -slots 32 -password 1111
Получаю ошибку:
Python
1
2
3
4
5
6
7
8
Traceback (most recent call last):
  File "/home/cp/gameservers.py", line 266, in <module>
    elif not serverConfigure():
  File "/home/cp/gameservers.py", line 111, in serverConfigure
    data = f.read()
  File "/usr/lib/python3.2/codecs.py", line 300, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 2: invalid continuation byte
Вот сам код:
Кликните здесь для просмотра всего текста

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#! /usr/bin/python3
 
# gameservers.py
#       -action     [install|reinstall|start|stop|restart|delete|updatepassword|sysload]
#       -sid
#       -game
#       -ip
#       -port
#       -slots
#       -password
 
# Ports:
# Port #1 = port
# Port #2 = port + 1
# Port #3 = port + 1000
 
import sys
import os
import re
import json
import crypt
import hashlib
import datetime
import argparse
 
# Parse arguments
argParser = argparse.ArgumentParser(description='LitePanel server-side.')
argParser.add_argument("-action", type=str,
                    choices=['install', 'reinstall', 'start', 'stop', 'restart', 'delete', 'updatepassword', 'sysload'],
                    help="Action", required=True)
argParser.add_argument("-sid", type=int,
                    help="Server ID", required=True)
argParser.add_argument("-game", type=str,
                    choices=[os.path.splitext(os.path.basename(f))[0] for f in os.listdir("/home/cp/gameservers/configs/")],
                    help="Game code", required=True)
argParser.add_argument("-ip", type=str,
                    help="IP", required=True)
argParser.add_argument("-port", type=int,
                    help="Port", required=True)
argParser.add_argument("-slots", type=int,
                    help="Slots ammount", required=True)
argParser.add_argument("-password", type=str,
                    help="Password", required=True)
args = argParser.parse_args()
 
action      =   str(args.action)
serverid    =   int(args.sid)
game        =   str(args.game)
ip          =   str(args.ip)
port        =   int(args.port)
slots       =   int(args.slots)
password    =   str(args.password)
 
salt = 'tlas'
username = 'gs' + str(serverid)
 
gameConfig = None
 
def md5file(filePath):
    f = open(filePath, 'rb')
    md5 = hashlib.md5()
    while True:
        data = f.read(8192)
        if not data:
            break
        md5.update(data)
    f.close()
    return md5.hexdigest()
 
def loadGameConfig():
    global gameConfig
    f = open('/home/cp/gameservers/configs/' + game + '.cfg', 'r')
    data = f.read()
    gameConfig = json.loads(data)
    f.close()
 
def serverStatus():
    p = os.popen('su -lc "screen -ls | grep -c gameserver" ' + username)
    count = int(p.readline())
    p.close()
    if count > 0:
        return True
    else:
        return False
 
def serverCheckFiles():
    for file in gameConfig['Files']:
        if not os.path.isfile('/home/' + username + file['File']):
            if file['Required'] == 1:
                return False
            else:
                continue
        
        fileHash = md5file('/home/' + username + file['File'])
        if not fileHash in file['Hashes']:
            return False
    return True
 
def serverConfigure():
    configs = gameConfig['Configs']
    for config in configs:
        # Check config file
        if not os.path.isfile('/home/' + username + config['File']):
            if config['Required'] == 1:
                return False
            else:
                continue
        
        # Read config
        f = open('/home/' + username + config['File'], 'r', encoding='utf-8')
        data = f.read()
        f.close()
        
        # Append exec configs
        if(config['ExecPattern']):
            execPattern = config['ExecPattern'].replace("<value>", "([^\s]*)");
            execConfigs = re.findall(execPattern, data)
            for execConfig in execConfigs:
                configPath = os.path.dirname(config['File']) + '/' + execConfig
                configs.append({
                    "File": configPath,
                    "Required": 0,
                    "ExecPattern": config['ExecPattern'],
                    "Values": [dict(i, Required = 0) for i in config['Values']]
                })
        
        # Check configs values
        for value in config['Values']:
            pattern = value['Pattern'].replace('<value>', '(.*)')
            
            # IP value
            if value['Value'] == '__ip__':
                replace = value['Pattern'].replace('<value>', ip)
            # Port value
            elif value['Value'] == '__port__':
                replace = value['Pattern'].replace('<value>', str(port))
            # Port 2 value
            elif value['Value'] == '__port2__':
                replace = value['Pattern'].replace('<value>', str(port + 1))
            # Port 3 value
            elif value['Value'] == '__port3__':
                replace = value['Pattern'].replace('<value>', str(port + 1000))
            # Slots value
            elif value['Value'] == '__slots__':
                replace = value['Pattern'].replace('<value>', str(slots))
            # Other values
            else:
                replace = value['Pattern'].replace('<value>', value['Value'])
            
            data = re.sub(pattern, replace, data)
            
            # Required, but not found
            if value['Required'] == 1 and not re.search(pattern, data):
                return False
            # Not required, but found
            elif value['Required'] == -1 and re.search(pattern, data):
                return False
        
        # Rewrite config
        f = open('/home/' + username + config['File'], 'w', encoding='utf-8')
        f.write(data)
        f.close()
    return True
 
def serverInstall():
    os.system('useradd -m -g gameservers -p ' + crypt.crypt(password, salt) + ' ' + username)
    for archive in gameConfig['Archives']:
        os.system('tar -xf /home/cp/gameservers/files/' + archive + '.tar -C /home/' + username + '/')
    os.system('chown ' + username + ' -Rf /home/' + username)
    os.system('chmod 700 /home/' + username)
    return True
 
def serverReinstall():
    os.system('rm -Rf /home/' + username + '/*')
    for archive in gameConfig['Archives']:
        os.system('tar -xf /home/cp/gameservers/files/' + archive + '.tar -C /home/' + username + '/')
    os.system('chown ' + username + ' -Rf /home/' + username)
    return True
 
def serverStart():
    execCmd = gameConfig['ExecCmd']
    execCmd = execCmd.replace('@ip@', ip)
    execCmd = execCmd.replace('@port@', str(port))
    execCmd = execCmd.replace('@port2@', str(port+1))
    execCmd = execCmd.replace('@port3@', str(port+1000))
    execCmd = execCmd.replace('@slots@', str(slots))
    os.system('su -lc "screen -AmdS gameserver ' + execCmd + '" ' + username)
    return True
 
def serverStop():
    os.system('su -lc "screen -r gameserver -X quit " ' + username)
    return True
 
def serverUpdatePassword():
    os.system('usermod -p ' + crypt.crypt(password, salt) + ' ' + username)
    return True
 
def serverDelete():
    os.system('userdel -rf ' + username)
    return True
 
def serverSysLoad():
    cpu = 0.0
    ram = 0.0
    
    p = os.popen("ps u -U gs" + str(serverid) + " | awk '{print $3\"\t\"$4}'")
    line = p.readline()
    
    while line:
        result = re.match("([0-9]+\.[0-9]+)\t([0-9]+\.[0-9]+)", line)
        if(result):
            cpu += float(result.group(1))
            ram += float(result.group(2))
        line = p.readline()
    
    p.close()
    print('[[' + str(cpu) + '::' + str(ram) + ']]')
 
def returnResult(status, description = ''):
    date = datetime.datetime.today()
    filename = date.strftime('%d-%m-%y') + '.xls'
    if os.path.isfile('/home/cp/logs/' + filename):
        # Open file
        f = open('/home/cp/logs/' + filename, 'a')
    else:
        # Create file
        f = open('/home/cp/logs/' + filename, 'w')
        f.write('TIME,SERVERID,STATUS,DESCRIPTION\n')
    
    f.write(date.strftime('%H:%M:%S') + ',' + str(serverid) + ',' + status + ',' + description + '\n')
    f.close()
    
    # Print result and exit
    print('[[' + status + '::' + description + ']]')
    exit(0)
 
loadGameConfig()
 
if action == 'install':
    if not serverInstall():
        returnResult('ERROR', 'InstallError')
    elif not serverConfigure():
        returnResult('ERROR', 'ConfigError')
    else:
        returnResult('OK')
 
if action == 'reinstall':
    if serverStatus():
        if not serverStop():
            returnResult('ERROR', 'StopError')
    
    if not serverReinstall():
        returnResult('ERROR', 'ReinstallError')
    elif not serverConfigure():
        returnResult('ERROR', 'ConfigError')
    else:
        returnResult('OK')
 
if action == 'start':
    if serverStatus():
        if not serverStop():
            returnResult('ERROR', 'StopError')
    
    if not serverCheckFiles():
        returnResult('ERROR', 'FilesError')
    elif not serverConfigure():
        returnResult('ERROR', 'ConfigError')
    elif not serverStart():
        returnResult('ERROR', 'StartError')
    else:
        returnResult('OK')
 
if action == 'stop':
    if not serverStop():
        returnResult('ERROR', 'StopError')
    else:
        returnResult('OK')
 
if action == 'restart':
    if not serverStop():
        returnResult('ERROR', 'StopError')
    elif not serverCheckFiles():
        returnResult('ERROR', 'FilesError')
    elif not serverConfigure():
        returnResult('ERROR', 'ConfigError')
    elif not serverStart():
        returnResult('ERROR', 'StartError')
    else:
        returnResult('OK')
 
if action == 'delete':
    if serverStatus():
        serverStop()
    
    if not serverDelete():
        returnResult('ERROR', 'DeleteError')
    else:
        returnResult('OK')
 
if action == 'updatepassword':
    if serverStatus():
        if not serverStop():
            returnResult('ERROR', 'StopError')
    
    if not serverUpdatePassword():
        returnResult('ERROR', 'UpdatePasswordError')
    else:
        returnResult('OK')
 
 
if action == 'sysload':
    serverSysLoad()
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
17.11.2013, 13:37
Ответы с готовыми решениями:

Перестало открывать и читать файлы
Работало все нормально щас буквально тока что перестало файлы открывать и читать from os import * def Readfile(): fname =...

Как правильно открывать файл и записывать/читать из него
Как правильно открывать файл и записывать/читать из него? На разных сайтах и учебниках есть различные примеры етого но везде разные ...

Файлы. Как заставить прогу всегда читать файлы из папки, в которой она сама?
Здравствуйте. Вобщем написал прогу, в ней используется относительный путь к файлам. Прога лежит в %ProgramFiles%\Свояпапка прикол в том,...

1
4866 / 3288 / 468
Регистрация: 10.12.2008
Сообщений: 10,570
17.11.2013, 21:37
1)
в третьем питоне файлы нужно открывать, указывая кодировку (всегда)
проблема, может, и не в этом, но надо поправить, прежде чем продолжать дебажить код

2)
пути к файлам склеиваются через os.path.join()

3)
судя по строке, он пытается в кодировке utf-8 прочитать файл, который не в этой кодировке
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
17.11.2013, 21:37
Помогаю со студенческими работами здесь

Каие программы могут считывать файлы с образа HDD диска и читать с него файлы как с физического диска ?
Здраствуйте ! подскажите пожалуйста какие программы могут читать образы HDD диска как физического диска и восстанавливать файлы с них ...

Как правильно открывать формы
Здравствуйте! Расскажите как правильно открыть форму. Проблема в том что я не знаю как открыть 1 форму из 3 формы К примеру form1 -&gt;...

Как открывать в Image файлы TIFF?
Подскажите, пожалуйста, как грузить и показывать TIFF картинку в элементе управления Image?

Как открывать файлы сторонних программ?
Здравствуйте, встала задача написать скрипт для открытия файлов разных программ по нажатию кнопки в скаде wincc 7.2 c помощью vba или vbs....

Как открывать в Image файлы TIFF?
Позарез нужно открывать в Image файлы TIFF!!!Подскажите,как?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11680&amp;d=1772460536 Одним из. . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru