1

Let's say I have a python script myscript.py, which takes multiple named arguments. The user calls the script as python myscript.py --arg1 value1 --arg2 value2. How to capture this whole command (i.e. python myscript.py --arg1 value1 --arg2 value2 ) and save it to a text file "command.selfie" using the same script that the user is calling?

1

2 Answers 2

3

sys.argv is a list with all the arguments. This will help:

import sys
command = " ".join(sys.argv)
# do whatever you want to do with command: str
Sign up to request clarification or add additional context in comments.

Comments

1

You can do something like this:

import argparse
import sys

def main(argv):
   parser = argparse.ArgumentParser()
   parser.add_argument("--arg1", default=False, help="Explain arg1")
   parser.add_argument("--arg2", type=str, default="hello", help="Explain arg2")
   # add all arguments you need

   args = parser.parse_args(argv[1:])       
   params = {"arg1": args.arg1,
             "arg2": args.arg2, }

   print(params["arg1"])
   print(params["arg2"])

if __name__ == "__main__":
   sys.exit(main(sys.argv))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.