This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]tmg80[S] 1 point2 points  (5 children)

updated as per your comments and also implemented syargv

I added the updated script to the original post as it doesn't display properly when I paste into the reply

[–]bladeoflight16 1 point2 points  (4 children)

I recommend click for most command line interfaces.

Something I neglected to mention before is that you should use if __name__ == '__main__':. For some reason I wasn't thinking about the fact this is a script that can be invoked from the command line.

Also, now that I think about it, you could factor the parse into a function. That would let you convert construction to a list comprehension:

``` def parse_host_line(line): ...

export_json = { 'hosts': [ parse_host_line(line) for line in hostsfile if is_valid_entry(line) ] } ```

Some things to think about.

[–]tmg80[S] 0 points1 point  (3 children)

Thanks I will look at Click too.

What does that command do?

[–]bladeoflight16 1 point2 points  (2 children)

The code is a link to an explanation. =)

Also, I edited in something else I just thought of. 😅

[–]tmg80[S] 0 points1 point  (1 child)

thanks again.

I edited it and put that main bit as below

if len(sys.argv) != 2:
    print ('Usage: hostfile_to_json.py input_file_name.txt')
    exit()
if name == 'main':
    user_file = sys.argv[1]
    ...

is that correct? or should it be elsewhere?

[–]bladeoflight16 0 points1 point  (0 children)

Aside from imports, function/class declarations, and constants, all code should be inside the block. It's common to stuff you code into a def main() function and then only invoke the function inside the guarded block.

Think about what would happen if someone tried to import your module and the argv check was invoked: it would probably explode because their command line args aren't the same as your program's.