0

I have below example code where it has three variable defined job_Name out_File err_File.

Now I'm looking to remove this from print statement if any of the variable or all the variables either empty ot not defined

job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

print("Job Name {0},Output {1}, Error {2}".format(job_Name,out_File,err_File))

ie: if job_Name is empty it should print :

Output  Error
/tmp/123 /tmp/321

Let suppose out_File and err_File not defined it should only print job_Name.

Job Name 
Test

This can be done with chain conditions if else etc.. but looking if that can be avoid as we have multiple such variables and achieved with some smarter or other elegant way.

3 Answers 3

1

A little extended but does the trick:

job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

headers = ''
output = ''
if job_Name:
    headers += 'Job Name\t'
if out_File:
    headers += 'Output\t'
if err_File:
    headers += 'Error\t'

for val in [job_Name, out_File, err_File]:
    if val:
        output += val + '\t'

print(headers)
print(output)

and another approach if your variables have the desired name to print could be this:

def retrieve_name(var):
    # prints the given variable's name
    import inspect
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]


job_Name = "Test"
out_File = "/tmp/123"
err_File = "/tmp/321"

headers = ''
output = ''

for val in [job_Name, out_File, err_File]:
    if val:
        headers += str(retrieve_name(val)[0]) + '\t'
        output += val + '\t'

print(headers)
print(output)
Sign up to request clarification or add additional context in comments.

Comments

1

Maybe this is a solution for you, but it'll depend on where those variables come from:

error_data = {
    "Job Name": "Test",
    "Output": "/tmp/123",
    "Error": "/tmp/321"
}
line = []
for description, value in error_data.items():
    if(value):
        line.append("{description} {value}".format(description=description, value=value))

print(",".join(line))

Comments

0

Perhaps you could do

print(f"{'Job Name' + job_Name + ', ' if job_Name else ''}{'Output' + out_File + ', ' if out_File else ''}{'Error' + err_File + ', ' if err_File else ''}")

1 Comment

...but it's neither nice nor a perfect solution with regards to the commas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.