personalt
personalt

Reputation: 850

Python write .sh script, newline character \n causes script to not be parsed correctly

I have the Python code below that is creating a large shell script.

I want to use the \n character to make a new line to keep the script looking clean but the \n appears to cause the shell not look past the first line.

If I edit the script in textpad or SublimeText it can strip the \n's and the script runs fine. I know \n is a new line but is there any way to get Python to write to separate lines without appending \n to the end?

fip6 = open("github_ip6.sh", "w", newline='') 
fip6.write('aws ec2 modify-managed-prefix-list \ ' + '\n')
fip6.write('    --prefix-list-id pl-047XXXXX \ ' + '\n')

for address in actions:
   if not is_ipv4_only(address):
   fip6.write('    --add-entries Cidr=' + address + ',Description=' + address + ' \ ' + '\n')

fip6.write("    --current-version 1")
fip6.close()

Upvotes: 0

Views: 318

Answers (1)

chepner
chepner

Reputation: 532303

You can use print and the file keyword argument:

with open("github_ip6.sh", "w") as fip6:
    print('aws ec2 modify-managed-prefix-list \\', file=fip6)
    print('    --prefix-list-id pl047XXXXX \\', file=fip6)
    for address in actions:
        if not is_ipv4_only(address):
            print(f'    --add-entries Cidr={address}, Description={address} \\', file=fip6)
    print('    --current-version 1', file=fip6)

You can also use a context manager from contextlib to temporarily replace sys.stdout with your output file.

from contextlib import redirect_stdout

with open("github_ip6.sh", "w") as fip6:
    with redirect_stdout(fip6):
        print('aws ec2 modify-managed-prefix-list \\')
        print('    --prefix-list-id pl047XXXXX \\')
        for address in actions:
            if not is_ipv4_only(address):
                print(f'    --add-entries Cidr={address}, Description={address} \\')
        print('    --current-version 1')

Upvotes: 1

Related Questions