How To Join All Arguments Passed To Python Vs Powershell Scripts
1 min readNov 16, 2021
The aim of this pageđź“ť is to document an idiom of joining arguments into a single string and then writing them into a file (the latter part is actually optional). For fun, comparing the python idiom that uses the .join
method the Powershell's use of operators (join
, >>
aka redirect operator and ..
aka range operator).
1. Pyth
#writer.py
import sys
if __name__ == "__main__":
f = open(sys.argv[1], mode="wt")
f.write(" ").join(sys.argv[2:])
f.close()
- if you want to have a script that creates
newfile.txt
and writes the rest of the text into it - you add this to the bottom of the module
argv
parses argumets into a list- create a file with the first argument using the
open()
method - utilize slicing to join the rest of the list into a string and write it into the file
- close the file with
close()
>>> python ./writer.py newfile.txt hello I want this to be written into newfile.txt
2. Posh
function writer {
echo (($args[1..($args.Length-1)]) -join " ") >> $args[0]
}
- in PowerShell you find all arguments in an automatic variable called
$args
- there is no slicing in posh
- but there is a range operator
..
so you can select items from index1
(second item) tolength-1
(last item) - there is a
-join
operator
â–¶ writer newfile.txt hello I want this to be written into newfile.txt