Always throw things in main
:
def main():
# code
main()
It might seem pointless but it does help with preventing global pollution, which is good if you ever decide to add a function somewhere.
Using
x = sys.argv[1]
is acceptable for a trivial script, but it's not much harder to use docopt
and implement a proper command-line parser:
"""
Name Of Program.
Usage: prog.py <pathname>
"""
import docopt
def main():
args = docopt.docopt(__doc__)
x = args["<pathname>"]
Trivial, but it gives you --help
, error reporting and sane handling of bad input, nearly for free.
This can be simplified a little with pathlib
:
parts = pathlib.PurePosixPath(args["<pathname>"]).parts
if len(parts) >= 2 and parts[0] == "/":
parts = ("/" + parts[1],) + parts[2:]
You can actually use just pathlib.Path
but it may assume a Windows format on Windows machines.
Your quoting:
parts = ["'" + i + "'" for i in parts]
should be done with repr
:
parts = map(repr, parts)
and the formatting should use .format
:
res = "file.path({})".format(",\n ".join(parts))
This gives
#!/usr/bin/env python3
"""
Name Of Program.
Usage: prog.py <pathname>
"""
import docopt
import pathlib
def main():
args = docopt.docopt(__doc__)
parts = pathlib.PurePosixPath(args["<pathname>"]).parts
if len(parts) >= 2 and parts[0] == "/":
parts = ("/" + parts[1],) + parts[2:]
args = ",\n ".join(map(repr, parts))
print("file.path({})".format(args))
main()
Technically PEP 8 says docopt
should be separated from pathlib
, the second being in the stdlib, but it looks nicer this way for now.