Search code examples
pythonargumentscommand-line-argumentsoptparse

Spawning a process with inherited python optparse options


I have a bunch of python scripts that use the optparse package. I'd like to give them all a "remote_run" option, which I'd like to use as follows:

if options.remote_run:
    cmd = create_cmd(options)
    os.system('ssh %s@%s "%s"' % (user, server, cmd))
    sys.exit(0)

The function create_cmd() should create a command that is equivalent to the command used to launch this process, except that the remote_run option is not set. The idea is for the script to outsource itself to a different server, in order to preserve the current server's resources.

What is the best way to do this? I did this one-off for a couple of the scripts by writing customized cmd-generating functions, but I have to keep those functions up-to-date whenever I add new options to those scripts, which is not ideal.


Solution

  • Based on Is it possible to set the python -O (optimize) flag within a script?:

    #!/usr/bin/env python
    import socket
    import subprocess
    import sys
    from pipes import quote
    
    def main():
        print(socket.gethostname())
        print(sys.argv)
    
    if __name__=="__main__":
       if '--remote-run' in sys.argv:
          sys.argv.remove('--remote-run')
          command = ' '.join(map(quote, ['python'] + sys.argv))
          sys.exit(subprocess.call(['ssh', '%s@%s' % (user, server), command]))
       else:
          main()