I'm looking to understand how custom file descriptors work in Python for input, output, defaults setup, and final closing. I have a file in Bash that does exactly what I want to do in Python. Can anyone tell me how this would be done in Python? I'm using Python 2.7.5, Bash 4.2, and executing on CentOS 7.3.
setup
$ echo "input string" > input
bash_fd.sh
#!/bin/bash
# Demonstration of custom file descriptors in Bash
# 3 script input (scrin)
# 4 script output (scrout)
# 5 script error (screrr)
# 6 script data (scrdata, demo: JSON return payload)
# 7 script log (scrlog)
fd_open()
{
### Provide defaults for file descriptors 3-7 ONLY if the FDs are undefined
{ >&3; } 2>/dev/null || exec 3<&0 # dup scrin to stdin
{ >&4; } 2>/dev/null || exec 4>&1 # dup scrout to stdout
{ >&5; } 2>/dev/null || exec 5>&2 # dup screrr to stderr
{ >&6; } 2>/dev/null || exec 6>/dev/null # set scrdata to /dev/null
{ >&7; } 2>/dev/null || exec 7>/dev/null # set scrlog to /dev/null
}
fd_close()
{
# Close all file descriptors
exec 3>&-
exec 4>&-
exec 5>&-
exec 6>&-
exec 7>&-
}
main()
{
fd_open # Ensure
echo "[$(date)] Program beginning" >&7 # scrlog
echo -n 'Enter a message: ' >&4 # scrout
read MSG <&3 # scrin
echo "Read message $MSG" >&4 # scrout
echo "[screrr] Read message $MSG" >&5 # screrr
echo "{\"msg\": \"$MSG\"}" >&6 # scrdata: return JSON payload
echo "[$(date)] Program finishing: $MSG" >&7 # scrlog
fd_close
return ${1:-0} # return status code
}
# For demonstration purposes, $1 is the return code returned when calling main
main "$1"
invocation
$ ./bash_fd.sh 37 3<input 4>scrout 5>screrr 6>scrdata 7>scrlog
$
return code
$ echo $?
37
generated files
$ cat scrout
Enter a message: Read message input string
$ cat screrr
[screrr] Read message input string
$ cat scrdata
{"msg": "input string"}
$ cat scrlog
[Wed Jun 14 21:33:24 EDT 2017] Program beginning
[Wed Jun 14 21:33:24 EDT 2017] Program finishing: input string
Any help in translating the above Bash script to Python will really help me understand Python and custom file descriptors and will be greatly appreciated.