How does this handle pipes and such? What's the nicest python equivalent to `grep ^$(whoami) /etc/passwd | awk -F : '{print $NF}'`?
# Option 1 (no pipes)
import os
for line in open("/etc/passwd").read().splitlines():
fields = line.split(":")
if fields[0] == os.getlogin():
print(fields[-1])
# Option 2 (Cheating, but not really. For most problems worth solving, there exists a library to do the work with little code.)
import os
print(os.environ['SHELL'])
# Option 3 (pipes, not sure if the utf-8 thing can be done nicer somehow)
import subprocess
username = subprocess.check_output("whoami", encoding="utf-8").rstrip()
p1 = subprocess.Popen(["grep", "^" + username, "/etc/passwd"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["awk", "-F", ":", "{print $NF}"], stdin=p1.stdout, stdout=subprocess.PIPE)
print(p2.communicate()[0].decode("utf-8")) subprocess.check_output("grep ^$(whoami) /etc/passwd | awk -F : '{print $NF}'", shell=True, encoding="utf-8").strip()
I didn't test that particular line, but in general this is how I execute shell pipelines in Python.In bash, you have to use commands for most things. In Python, you don't.
For example, `curl ... | jq ...` shell pipeline would be converted into requests/json API in Python.
Edit: The equivalent of above would be:
#!/usr/bin/perl
my $shell=(getpwuid($>))[8];
print "$shell\n";
Though it does have simple syntax for pipes as well. pwd.getpwnam(getpass.getuser()).pw_shell