Telling Sudo To Start nohup
In The Background
The &
puts sudo
itself in the background, so it can't reliably prompt for a password; if it can't prompt for a password, it won't get to the point where it ever starts nohup at all.
Take off the &
, and use -b
to tell sudo to put the thing that it starts (in this case nohup
) in the background.
sudo -b nohup python3 scriptName.py
Not Using nohup
At All
Better than this is to just not use nohup
at all. nohup is not a very useful tool; it only does three things:
- Redirect stdin to come from
/dev/null
if it's attached to a TTY.
- Redirect any of stdout and stderr that are attached to the TTY to go to
nohup.out
instead.
- Decline to forward HUP signals to its children.
Bash can do all those things itself; there's never a reason to use nohup from bash. Doing this under sudo might look like:
sudo bash -c '"$@" </dev/null >/dev/null 2>&1 & disown -h $!' _ \
python3 scriptName.py
Explaining how the above works:
- The
</dev/null >/dev/null 2>&1
does the same thing nohup's built-in redirections do (except using /dev/null
for output instead of a nohup.out
file).
- The
_
fills in $0
, so later arguments go into $1
and onward, becoming part of the "$@"
array which the inner shell invokes to kick off your actual command.
disown -h
tells bash not to forward HUP signals (not strictly necessary here since this is a noninteractive shell and that forwarding is only on-by-default in shells with job control enabled in the first place).