简体   繁体   中英

Python: What does the following code do?

Can someone please explain to me piece by piece, what the following does? My code won't run and this part was provided. I've tested all of my code in iPython notebook and everything works, so I don't know if the problem is because of this block below.

def main():
  args = sys.argv[1:]
  if not args:
    print 'usage: [--summaryfile] file [file ...]'
    sys.exit(1)
  summary = False
  if args[0] == '--summaryfile':
    summary = True
    del args[0]

  # ... my code ....

Update : I tried to do as Simon suggested. I opened up iPython and typed the following in the command line:

ipython 'assignment.py' --summaryfile

I tried variations of this and I keep getting a syntax error.

  1. How do I run this?
  2. Am I restricted to iPython only?

It basically checks to see if --summaryfile has been passed as an argument when you run the script

If no arguments have been passed, then it will print a line telling you how to use the script and then exit. summary is now set to false

If --summaryfile has been passed, then it will set summary = True and continue running the rest of your code

I'm not sure that you can enter arguments like that in ipython, so presumably your code will always exit because it doesnt find any arguments

EDIT:

For some reason I automatically associated ipython with ipython notebook. You can pass arguments with ipython. See here: How to pass command line arguments to ipython

In your case, try adding --summaryfile as an argument when you run your script through ipython

If you're running this from ipython notebook, there are a couple of things you can try:

  1. Remove that section of code and just set summary = True. The rest of your code should run, but without seeing everything its hard to say what impact this may have on the rest of your code

  2. You can save your script as a python .py file, and use ipython magic to run the code from within notebook. You can pass arguments when you're running that script from within notebook. Check this: https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-run

If you have all the code in a regular .py file (outside of a notebook) you can run and pass an argument using the command line. Navigate to the directory where the script file is and run ipython filename.py --summaryfile

A very rudimentary command line argument parser.

It checks for the command line except the executable's name itself ( sys.argv[1:] ). If it's empty, dump help message and fail. If the first argument is "--summaryfile" , set some flag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM