how to add transfer syntax uid to the filemeta of dataset - python

I use pydicom library to generate .dcm files using the datasets coming from the CT and MRI machines, however in that dataset, the tag (0002,0010) is missing. As I dont have that tag, I am not able to detect the transfer syntax whether it is implicit VR little endian, explicit VR little endian, jpeg lossless etc. I need the transfer syntax for saving the dataset with flags like below
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.file_meta.TransferSyntaxUID = JPEGLossless
ds.is_explicit_VR = True etc
If I dont use the above flags, then the dcm file that is generated will not be valid as there is no transfer syntax.
Since I dont know the transfer syntax, I am sending the transfer syntax in command line arguments when I run the program, and setting the above flags accordingly, and saving the dataset. I know this is wrong method but I just used it as a temporary solution. Is there any better way to detect the transfer syntax please as the tag (0002, 0010) is missing.
Below is my code that I use for saving the dcm file using the dataset coming from the CT machine. For now i am sending the transfer syntax as command line argument
from pynetdicom3 import AE, VerificationPresentationContexts, StoragePresentationContexts, QueryRetrievePresentationContexts
from pydicom.uid import ImplicitVRLittleEndian, ExplicitVRLittleEndian, JPEGLossless
from pynetdicom3.sop_class import CTImageStorage, MRImageStorage
from pynetdicom3 import pynetdicom_uid_prefix
from pydicom.dataset import Dataset, FileDataset
import argparse
import uuid
import os
import django
import logging
ttt = []
ttt.extend(VerificationPresentationContexts)
ttt.extend(StoragePresentationContexts)
ttt.extend(QueryRetrievePresentationContexts)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lh_dcm_viewer.settings')
django.setup()
from dcm_app.models import DCMFile, DCMFileException
def _setup_argparser():
parser = argparse.ArgumentParser(
description="The getscp application implements a Service Class "
"Provider (SCP) for the Query/Retrieve (QR) Service Class "
"and the Basic Worklist Management (BWM) Service Class. "
"getscp only supports query functionality using the C-GET "
"message. It receives query keys from an SCU and sends a "
"response. The application can be used to test SCUs of the "
"QR and BWM Service Classes.",
usage="getscp [options] port")
# Parameters
# Transfer Syntaxes
ts_opts = parser.add_argument_group('Preferred Transfer Syntaxes')
ts_opts.add_argument("--type",
help="prefer explicit VR local byte order (default)")
ts_opts.add_argument("--detect_transfer_syntax",
help="Detect transfer syntax")
ts_opts.add_argument("--port",
help="port at which the SCP listens")
return parser.parse_args()
args = _setup_argparser()
ae = AE(ae_title=b'MY_ECHO_SCP', port=int(args.port))
if args.type == "jpeg_lossless":
ae.add_supported_context('1.2.840.10008.1.2.4.57')
elif args.type == "implicit":
ae.add_supported_context('1.2.840.10008.1.2')
print("ImplicitVRLittleEndian")
elif args.type == "explicit":
ae.add_supported_context('1.2.840.10008.1.2.1')
ae.requested_contexts = ttt
ae.supported_contexts = ttt
DICOM_IP = '192.168.1.11'
DICOM_IP = '127.0.0.1'
DICOM_PORT = 5678
def save_file(dataset, context, info):
try:
random_str = uuid.uuid4().hex
meta = Dataset()
meta.MediaStorageSOPClassUID = dataset.SOPClassUID
meta.MediaStorageSOPInstanceUID = dataset.SOPInstanceUID
meta.ImplementationClassUID = pynetdicom_uid_prefix
meta.FileMetaInformationGroupLength = 202
received_file_path = "../received_dcms/%s.dcm" % random_str
dataset_vr = None
try:
dataset_vr = dataset[("6000", "3000")].VR
except KeyError:
pass
print(dataset_vr)
if args.type == "implicit" or dataset_vr == "OB or OW":
ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
ds.update(dataset)
ds.is_little_endian = True
ds.is_implicit_VR = True
if(dataset_vr == "OB or OW"):
print("forced ImplicitVRLittleEndian")
ds.file_meta.TransferSyntaxUID = ImplicitVRLittleEndian
elif args.type == "jpeg_lossless":
ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
ds.update(dataset)
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.file_meta.TransferSyntaxUID = JPEGLossless
ds.is_explicit_VR = True
elif args.type == "explicit":
meta.TransferSyntaxUID = "1.2.840.10008.1.2.1"
ds = FileDataset(received_file_path, {}, file_meta=meta, preamble=b"\0" * 128)
ds.update(dataset)
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.file_meta.TransferSyntaxUID = ExplicitVRLittleEndian
ds.is_explicit_VR = True
ds.save_as(received_file_path)
f = open(received_file_path, "rb")
f.close()
return 0XC200
return status
except Exception as e:
logger.error(e)
ae.on_c_store = save_file
ae.start()

I hate to send you away but this is a very specialized tool and it has it's own support community. I looked up your issue and found it might be a bug. There is a user who is having a similar problem and he said the transfer syntax is not missing if he uses an older version of the library.
SIMILAR ISSUE:
https://groups.google.com/forum/#!topic/pydicom/Oxd7cbCwseU
Support for this library is found here:
https://groups.google.com/forum/#!forum/pydicom
The code itself is maintained on GitHub where you can open bug reports and view all other bug reports: https://github.com/pydicom/pydicom/issues

Related

get audio device GUID in Python

I am trying to get GUID of audio device. The GUID can be found in registry Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\ the guid should look like {0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}
basically like this. but I want in python Getting GUID of audio output device (speaker,headphones)
I've tried myself but only thing I can find is to use command line and parse it in Python
import subprocess
sd = subprocess.run(
["pnputil", "/enum-devices", "/connected", "/class", "AudioEndpoint"],
capture_output=True,
text=True,
)
output = sd.stdout.split("\n")[1:-1]
def getDevices(devices):
deviceList = {}
for device in range(len(devices)):
if "Instance ID:" in devices[device]:
deviceList[devices[device+1].split(":")[-1].strip()] = devices[device].split("\\")[-1].strip()
return deviceList
print(getDevices(output))
which got me
{'Headset (Soundcore Life Q30 Hands-Free)': '{0.0.0.00000000}.{4ac89ef7-f00d-4069-b96b-421bd3276295}', 'Speakers (Echo Dot-BQP)': '{0.0.0.00000000}.{8085b216-297a-4d02-bc3d-83b997b79524}', 'Headphones (Soundcore Life Q30)': '{0.0.0.00000000}.{37e73048-025a-47ea-bf9f-59d5ef8f2b43}'}
Hopping there is better way
from __future__ import print_function
import comtypes
from pycaw.pycaw import AudioUtilities, IMMDeviceEnumerator, EDataFlow, DEVICE_STATE
from pycaw.constants import CLSID_MMDeviceEnumerator
def MyGetAudioDevices(direction="in", State = DEVICE_STATE.ACTIVE.value):
devices = []
# for all use EDataFlow.eAll.value
if direction == "in":
Flow = EDataFlow.eCapture.value # 1
else:
Flow = EDataFlow.eRender.value # 0
deviceEnumerator = comtypes.CoCreateInstance(
CLSID_MMDeviceEnumerator,
IMMDeviceEnumerator,
comtypes.CLSCTX_INPROC_SERVER)
if deviceEnumerator is None:
return devices
collection = deviceEnumerator.EnumAudioEndpoints(Flow, State)
if collection is None:
return devices
count = collection.GetCount()
for i in range(count):
dev = collection.Item(i)
if dev is not None:
if not ": None" in str(AudioUtilities.CreateDevice(dev)):
devices.append(AudioUtilities.CreateDevice(dev))
return devices
output_device = MyGetAudioDevices("out")
input_device = MyGetAudioDevices("in")
print(output_device)
print(input_device)
This worked for me

Get data as dataframe from Look through API sdk package in python

I have the following code to get a look from Looker through an API. I stored the api in a .ini. All of that works, but now I want to get the data from this look as Dataframe in python, so that I can use the data for further analysis. How can i do that? I used this code, but that only saves it to png. I can't find a way to create a dataframe from this, as I want the data itself and not just the outcome image.
import sys
import textwrap
import time
import looker_sdk
from looker_sdk import models
sdk = looker_sdk.init40("/Name.ini")
def get_look(title: str) -> models.Look:
title = title.lower()
look = next(iter(sdk.search_looks(title=title)), None)
if not look:
raise Exception(f"look '{title}' was not found")
return look
def download_look(look: models.Look, result_format: str, width: int, height: int):
"""Download specified look as png/jpg"""
id = int(look.id)
task = sdk.create_look_render_task(id, result_format, width, height,)
if not (task and task.id):
raise sdk.RenderTaskError(
f"Could not create a render task for '{look.title}'"
)
# poll the render task until it completes
elapsed = 0.0
delay = 0.5 # wait .5 seconds
while True:
poll = sdk.render_task(task.id)
if poll.status == "failure":
print(poll)
raise Exception(f"Render failed for '{look.title}'")
elif poll.status == "success":
break
time.sleep(delay)
elapsed += delay
print(f"Render task completed in {elapsed} seconds")
result = sdk.render_task_results(task.id)
filename = f"{look.title}.{result_format}"
with open(filename, "wb") as f:
f.write(result)
print(f"Look saved to '{filename}'")
look_title = sys.argv[1] if len(sys.argv) > 1 else "Name"
image_width = int(sys.argv[2]) if len(sys.argv) > 2 else 545
image_height = int(sys.argv[3]) if len(sys.argv) > 3 else 842
image_format = sys.argv[4] if len(sys.argv) > 4 else "png"
if not look_title:
raise Exception(
textwrap.dedent(
"""
Please provide: <lookTitle> [<img_width>] [<img_height>] [<img_format>]
img_width defaults to 545
img_height defaults to 842
img_format defaults to 'png'"""
)
)
look = get_look(look_title)
#Dataframe storage
download_look(look, image_format, image_width, image_height)
The SDK function you are using (create_look_render_task), which is described here only allows you to download in either pdf, png, or jpg.
If you want to get the data from a Look into a dataframe then you may want to look into using the run_look function instead described here. When you use run_look you can change the result_format to CSV and then write your own code to convert to a dataframe.

Custom audio input bytes to azure cognitive speech translation service in Python

I am in need to able to translate custom audio bytes which I can get from any source and translate the voice into the language I need (currently Hindi). I have been trying to pass custom audio bytes using following code in Python:
import azure.cognitiveservices.speech as speechsdk
from azure.cognitiveservices.speech.audio import AudioStreamFormat, PullAudioInputStream, PullAudioInputStreamCallback, AudioConfig, PushAudioInputStream
speech_key, service_region = "key", "region"
channels = 1
bitsPerSample = 16
samplesPerSecond = 16000
audioFormat = AudioStreamFormat(samplesPerSecond, bitsPerSample, channels)
class CustomPullAudioInputStreamCallback(PullAudioInputStreamCallback):
def __init__(self):
return super(CustomPullAudioInputStreamCallback, self).__init__()
def read(self, file_bytes):
print (len(file_bytes))
return len(file_bytes)
def close(self):
return super(CustomPullAudioInputStreamCallback, self).close()
class CustomPushAudioInputStream(PushAudioInputStream):
def write(self, file_bytes):
print (type(file_bytes))
return super(CustomPushAudioInputStream, self).write(file_bytes)
def close():
return super(CustomPushAudioInputStream, self).close()
translation_config = speechsdk.translation.SpeechTranslationConfig(subscription=speech_key, region=service_region)
fromLanguage = 'en-US'
toLanguage = 'hi'
translation_config.speech_recognition_language = fromLanguage
translation_config.add_target_language(toLanguage)
translation_config.voice_name = "hi-IN-Kalpana-Apollo"
pull_audio_input_stream_callback = CustomPullAudioInputStreamCallback()
# pull_audio_input_stream = PullAudioInputStream(pull_audio_input_stream_callback, audioFormat)
# custom_pull_audio_input_stream = CustomPushAudioInputStream(audioFormat)
audio_config = AudioConfig(use_default_microphone=False, stream=pull_audio_input_stream_callback)
recognizer = speechsdk.translation.TranslationRecognizer(translation_config=translation_config,
audio_config=audio_config)
def synthesis_callback(evt):
size = len(evt.result.audio)
print('AUDIO SYNTHESIZED: {} byte(s) {}'.format(size, '(COMPLETED)' if size == 0 else ''))
if size > 0:
t_sound_file = open("translated_output.wav", "wb+")
t_sound_file.write(evt.result.audio)
t_sound_file.close()
recognizer.stop_continuous_recognition_async()
def recognized_complete(evt):
if evt.result.reason == speechsdk.ResultReason.TranslatedSpeech:
print("RECOGNIZED '{}': {}".format(fromLanguage, result.text))
print("TRANSLATED into {}: {}".format(toLanguage, result.translations['hi']))
elif evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
print("RECOGNIZED: {} (text could not be translated)".format(result.text))
elif evt.result.reason == speechsdk.ResultReason.NoMatch:
print("NOMATCH: Speech could not be recognized: {}".format(result.no_match_details))
elif evt.reason == speechsdk.ResultReason.Canceled:
print("CANCELED: Reason={}".format(result.cancellation_details.reason))
if result.cancellation_details.reason == speechsdk.CancellationReason.Error:
print("CANCELED: ErrorDetails={}".format(result.cancellation_details.error_details))
def receiving_bytes(audio_bytes):
# audio_bytes contain bytes of audio to be translated
recognizer.synthesizing.connect(synthesis_callback)
recognizer.recognized.connect(recognized_complete)
pull_audio_input_stream_callback.read(audio_bytes)
recognizer.start_continuous_recognition_async()
receiving_bytes(audio_bytes)
Output:
Error: AttributeError: 'PullAudioInputStreamCallback' object has no attribute '_impl'
Packages and their versions:
Python 3.6.3
azure-cognitiveservices-speech 1.11.0
File Translation can be successfully performed but I do not want to save files for each chunk of bytes I receive.
Can you me pass custom audio bytes to the Azure Speech Translation Service and get the result in Python? If yes then how?
I got the solution to the problem by myself. I think it works with PullAudioInputStream too. But it worked for me using PushAudioInputStream. You don't need to create custom classes it would work like the following:
import azure.cognitiveservices.speech as speechsdk
from azure.cognitiveservices.speech.audio import AudioStreamFormat, PullAudioInputStream, PullAudioInputStreamCallback, AudioConfig, PushAudioInputStream
from threading import Thread, Event
speech_key, service_region = "key", "region"
channels = 1
bitsPerSample = 16
samplesPerSecond = 16000
audioFormat = AudioStreamFormat(samplesPerSecond, bitsPerSample, channels)
translation_config = speechsdk.translation.SpeechTranslationConfig(subscription=speech_key, region=service_region)
fromLanguage = 'en-US'
toLanguage = 'hi'
translation_config.speech_recognition_language = fromLanguage
translation_config.add_target_language(toLanguage)
translation_config.voice_name = "hi-IN-Kalpana-Apollo"
# Remove Custom classes as they are not needed.
custom_push_stream = speechsdk.audio.PushAudioInputStream(stream_format=audioFormat)
audio_config = AudioConfig(stream=custom_push_stream)
recognizer = speechsdk.translation.TranslationRecognizer(translation_config=translation_config, audio_config=audio_config)
# Create an event
synthesis_done = Event()
def synthesis_callback(evt):
size = len(evt.result.audio)
print('AUDIO SYNTHESIZED: {} byte(s) {}'.format(size, '(COMPLETED)' if size == 0 else ''))
if size > 0:
t_sound_file = open("translated_output.wav", "wb+")
t_sound_file.write(evt.result.audio)
t_sound_file.close()
# Setting the event
synthesis_done.set()
def recognized_complete(evt):
if evt.result.reason == speechsdk.ResultReason.TranslatedSpeech:
print("RECOGNIZED '{}': {}".format(fromLanguage, result.text))
print("TRANSLATED into {}: {}".format(toLanguage, result.translations['hi']))
elif evt.result.reason == speechsdk.ResultReason.RecognizedSpeech:
print("RECOGNIZED: {} (text could not be translated)".format(result.text))
elif evt.result.reason == speechsdk.ResultReason.NoMatch:
print("NOMATCH: Speech could not be recognized: {}".format(result.no_match_details))
elif evt.reason == speechsdk.ResultReason.Canceled:
print("CANCELED: Reason={}".format(result.cancellation_details.reason))
if result.cancellation_details.reason == speechsdk.CancellationReason.Error:
print("CANCELED: ErrorDetails={}".format(result.cancellation_details.error_details))
recognizer.synthesizing.connect(synthesis_callback)
recognizer.recognized.connect(recognized_complete)
# Read and get data from an audio file
open_audio_file = open("speech_wav_audio.wav", 'rb')
file_bytes = open_audio_file.read()
# Write the bytes to the stream
custom_push_stream.write(file_bytes)
custom_push_stream.close()
# Start the recognition
recognizer.start_continuous_recognition()
# Waiting for the event to complete
synthesis_done.wait()
# Once the event gets completed you can call Stop recognition
recognizer.stop_continuous_recognition()
I have used Event from thread since start_continuous_recognition starts in a different thread and you won't get data from callback events if you don't use threading. synthesis_done.wait will solve this problem by waiting for the event to complete and only then will call the stop_continuous_recognition. Once you obtain the audio bytes you can do whatever you wish in the synthesis_callback. I have simplified the example and took bytes from a wav file.
The example code provided uses a callback as the stream parameter to AudioConfig, which doesn’t seem to be allowed.
This code should work without throwing an error:
pull_audio_input_stream_callback = CustomPullAudioInputStreamCallback()
pull_audio_input_stream = PullAudioInputStream(pull_stream_callback=pull_audio_input_stream_callback, stream_format=audioFormat)
audio_config = AudioConfig(use_default_microphone=False, stream=pull_audio_input_stream)

How to log into SAP silently using win32com methods?

I have a question about SAP silent logon which I implemented using win32com this way
from win32com.client import Dispatch
R3 = Dispatch("SAP.Functions")
R3.Conn.System = 'xxx'
R3.Conn.Client = '100'
# other values needed to pass to R3.Conn
R3.Conn.logon #here is the problem
In VB i can use R3.Conn.Logon(1, True) to make logon siliencely. But in Python Logon seems not to be a method and do not allow me to pass parameters to it.
I tried using R3.Conn.Logon(1, True) in Python, but it returned an error
Logon was not callable.
How should I call silent logon in Python?
Thanks
This works for me.
Still experimenting, I want to add field selection and of course a filter to the RFC_READ_TABLE. But the connection works.
from win32com.client import Dispatch
Functions = Dispatch("SAP.Functions")
Functions.Connection.Client = "000"
Functions.Connection.ApplicationServer = "your server"
Functions.Connection.Language = "EN"
Functions.Connection.User = "you"
Functions.Connection.Password = "your pass"
Functions.Connection.SystemNumber = "00"
Functions.Connection.UseSAPLogonIni = False
if (Functions.Connection.Logon (0,True) == True):
print("Logon OK")
RfcCallTransaction = Functions.Add("RFC_READ_TABLE")
strExport1 = RfcCallTransaction.exports("QUERY_TABLE")
strExport2 = RfcCallTransaction.exports("DELIMITER")
strExport3 = RfcCallTransaction.exports("ROWSKIPS")
strExport4 = RfcCallTransaction.exports("ROWCOUNT")
tblOptions = RfcCallTransaction.Tables("OPTIONS")
#RETURNED DATA
tblData = RfcCallTransaction.Tables("DATA")
tblFields = RfcCallTransaction.Tables("FIELDS")
strExport1.Value = 'AGR_DEFINE'
strExport2.Value = ";"
strExport3.Value = 0
strExport4.Value = 10
if RfcCallTransaction.Call == True:
print ("Function call successful")
#print (tblData.RowCount)
j = 1
while j < tblData.RowCount:
print (tblData(j,"WA"))
j = j + 1

Userfriendly way of handling config files in python?

I want to write a program that sends an e-mail to one or more specified recipients when a certain event occurs. For this I need the user to write the parameters for the mail server into a config. Possible values are for example: serveradress, ports, ssl(true/false) and a list of desired recipients.
Whats the user-friendliest/best-practice way to do this?
I could of course use a python file with the correct parameters and the user has to fill it out, but I wouldn't consider this user friendly. I also read about the 'config' module in python, but it seems to me that it's made for creating config files on its own, and not to have users fill the files out themselves.
Are you saying that the fact that the config file would need to be valid Python makes it unfriendly? It seems like having lines in a file like:
server = 'mail.domain.com'
port = 25
...etc would be intuitive enough while still being valid Python. If you don't want the user to have to know that they have to quote strings, though, you might go the YAML route. I use YAML pretty much exclusively for config files and find it very intuitive, and it would also be intuitive for an end user I think (though it requires a third-party module - PyYAML):
server: mail.domain.com
port: 25
Having pyyaml load it is simple:
>>> import yaml
>>> yaml.load("""a: 1
... b: foo
... """)
{'a': 1, 'b': 'foo'}
With a file it's easy too.
>>> with open('myconfig.yaml', 'r') as cfile:
... config = yaml.load(cfile)
...
config now contains all of the parameters.
I doesn't matter technically proficient your users are; you can count on them to screw up editing a text file. (They'll save it in the wrong place. They'll use MS Word to edit a text file. They'll make typos.) I suggest making a gui that validates the input and creates the configuration file in the correct format and location. A simple gui created in Tkinter would probably fit your needs.
I've been using ConfigParser. It's designed to read .ini style files that have:
[section]
option = value
It's quite easy to use and the documentation is pretty easy to read. Basically you just load the whole file into a ConfigParser object:
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('configfile.txt')
Then you can make sure the users haven't messed anything up by checking the options. I do so with a list:
OPTIONS =
['section,option,defaultvalue',
.
.
.
]
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not config.has_option(section,option):
print "Missing option %s in section %s" % (option,section)
Getting the values out is easy too.
val = config.get('section','option')
And I also wrote a function that creates a sample config file using that OPTIONS list.
new_config = ConfigParser.ConfigParser()
for opt in OPTIONS:
section,option,defaultval = opt.split(',')
if not new_config.has_section(section):
new_config.add_section(section)
new_config.set(section, option, defaultval)
with open("sample_configfile.txt", 'wb') as newconfigfile:
new_config.write(newconfigfile)
print "Generated file: sample_configfile.txt"
What are the drawbacks of such a solution:
ch = 'serveradress = %s\nport = %s\nssl = %s'
a = raw_input("Enter the server's address : ")
b = 'a'
bla = "\nEnter the port : "
while not all(x.isdigit() for x in b):
b = raw_input(bla)
bla = "Take care: you must enter digits exclusively\n"\
+" Re-enter the port (digits only) : "
c = ''
bla = "\nChoose the ssl option (t or f) : "
while c not in ('t','f'):
c = raw_input(bla)
bla = "Take care: you must type f or t exclusively\n"\
+" Re-choose the ssl option : "
with open('configfile.txt','w') as f:
f.write(ch % (a,b,c))
.
PS
I've read in the jonesy's post that the value in a config file may have to be quoted. If so, and you want the user not to have to write him/her-self the quotes, you simply add
a = a.join('""')
b = b.join('""')
c = c.join('""')
.
EDIT
ch = 'serveradress = %s\nport = %s\nssl = %s'
d = {0:('',
"Enter the server's address : "),
1:("Take care: you must enter digits exclusively",
"Enter the port : "),
2:("Take care: you must type f or t exclusively",
"Choose the ssl option (t or f) : ") }
def func(i,x):
if x is None:
return False
if i==0:
return True
elif i==1:
try:
ess = int(x)
return True
except:
return False
elif i==2:
if x in ('t','f'):
return True
else:
return False
li = len(d)*[None]
L = range(len(d))
while True:
for n in sorted(L):
bla = d[n][1]
val = None
while not func(n,val):
val = raw_input(bla)
bla = '\n '.join(d[n])
li[n] = val.join('""')
decision = ''
disp = "\n====== If you choose to process, =============="\
+"\n the content of the file will be :\n\n" \
+ ch % tuple(li) \
+ "\n==============================================="\
+ "\n\nDo you want to process (type y) or to correct (type c) : "
while decision not in ('y','c'):
decision = raw_input(disp)
disp = "Do you want to process (type y) or to correct (type c) ? : "
if decision=='y':
break
else:
diag = False
while not diag:
vi = '\nWhat lines do you want to correct ?\n'\
+'\n'.join(str(j)+' - '+line for j,line in enumerate((ch % tuple(li)).splitlines()))\
+'\nType numbers of lines belonging to range(0,'+str(len(d))+') separated by spaces) :\n'
to_modify = raw_input(vi)
try:
diag = all(int(entry) in xrange(len(d)) for entry in to_modify.split())
L = [int(entry) for entry in to_modify.split()]
except:
diag = False
with open('configfile.txt','w') as f:
f.write(ch % tuple(li))
print '-*- Recording of the config file : done -*-'

Categories

Resources