Обновление и сохранение Python во время выполнения
Я не был уверен, как сформулировать заголовок этого вопроса.
Есть ли в Python метод, который будет принимать входные данные из терминала и записывать их в скрипт и сохранять эти изменения? Другими словами, скрипт будет автоматически обновляться. Пользователь вводит некоторую последовательность символов в приглашении, и сценарий записывает эти символы в тело сценария. В следующий раз, когда скрипт будет выполнен, эти персонажи будут доступны для справки.
2 ответа
Вы можете переписать исходный файл, да. Это просто файл, а чтение и запись файлов в Python вполне осуществимы. Python загружает исходные файлы только один раз, поэтому их перезапись, безусловно, возможна.
Но было бы гораздо проще просто использовать отдельный файл для записи последовательности и прочитать его из этого файла при следующем запуске кода.
В Python имеется любое количество модулей сохранения данных, которые могут упростить чтение и запись последовательности в файлах. Или вы можете повторно использовать стандарты сериализации данных, такие как JSON, для обработки чтения и записи. Это было бы намного легче поддерживать.
Следующий скрипт начинается со строк 2 и 3, не содержащих имен файлов -
#! /usr/bin/env python3
#
#
import os.path
no_file_1, no_file_2 = False, False
#open the file containing this script and read, by line, into list 'a', close this file
thisfile = open('__file__','r')
a = []
while True:
file_line = thisfile.readline()
if not file_line:
break
else:
a.append(file_line)
thisfile.close()
#extract the file names from line 2 and 3 of this file (one file name per line)
file_1, file_2 = a [1], a [2]
file_1, file_2 = file_1[1:-1], file_2[1:-1]
#if there are no file(s) listed in line 2 and 3, prompt the user for file name(s)
#and write the file name(s) w/ extenstion '.txt' to a[1] and a[2]
if file_1 == '':
no_file_1 = True
if file_2 == '':
no_file_2 = True
if no_file_1:
file_1 = input('Enter 1st File Name (no extension) >>> ')
a [1] = '#' + file_1 + '.txt' + '\n'
if no_file_2:
file_2 = input('Enter 2nd File Name (no extension) >>> ')
a [2] = '#' + file_2 + '.txt' + '\n'
#... then write a[new script] to this script
if no_file_1 or no_file_2:
thisfile = open(__file__, 'w')
for i in a:
thisfile.write(i)
#now that this script contains file names in lines 2 and 3, check to see if they exist
#in the same directory as this script ... if not, create them.
file_1, file_2 = a [1], a [2]
file_1, file_2 = file_1[1:-1], file_2[1:-1]
if not os.path.exists(file_1):
open(file_1, 'w')
#write to file_1.txt
if not os.path.exists(file_2):
open(file_2, 'w')
thisfile.close()
print(file_1,file_2)
Сценарий выполняется, проверяет и не находит имен файлов в строках 2 и 3. Пользователь вводит два имени файла, и сценарий перезаписывает себя правильными именами файлов, проверяет, существуют ли два файла, если нет, сценарий создает их.
Enter 1st File Name (no extension) >>> file_1
Enter 2nd File Name (no extension) >>> file_2
При следующем выполнении сценария имена файлов определяются в строках 2 и 3, и сценарий проверяет, существуют ли они, если нет, сценарий создает их.
#! /usr/bin/env python3
#file_1.txt
#file_2.txt
import os.path
no_file_1, no_file_2 = False, False
#open the file containing this script and read, by line, into list 'a', close this file
thisfile = open(__file__,'r')
a = []
while True:
file_line = thisfile.readline()
if not file_line:
break
else:
a.append(file_line)
thisfile.close()
#extract the file names from line 2 and 3 of this file (one file name per line)
file_1, file_2 = a [1], a [2]
file_1, file_2 = file_1[1:-1], file_2[1:-1]
#if there are no file(s) listed in line 2 and 3, prompt the user for file name(s)
#and write the file name(s) w/ extenstion '.txt' to a[1] and a[2]
if file_1 == '':
no_file_1 = True
if file_2 == '':
no_file_2 = True
if no_file_1:
file_1 = input('Enter 1st File Name (no extension) >>> ')
a [1] = '#' + file_1 + '.txt' + '\n'
if no_file_2:
file_2 = input('Enter 2nd File Name (no extension) >>> ')
a [2] = '#' + file_2 + '.txt' + '\n'
#... then write a[new script] to this script
if no_file_1 or no_file_2:
thisfile = open(__file__, 'w')
for i in a:
thisfile.write(i)
#now that this script contains file names in lines 2 and 3, check to see if they exist
#in the same directory as this script ... if not, create them.
file_1, file_2 = a [1], a [2]
file_1, file_2 = file_1[1:-1], file_2[1:-1]
if not os.path.exists(file_1):
open(file_1, 'w')
#write to file_1.txt
if not os.path.exists(file_2):
open(file_2, 'w')
thisfile.close()
print(file_1,file_2)