Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for when sys.argv is used in examples #252

Merged
merged 2 commits into from Jul 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGES.rst
Expand Up @@ -13,6 +13,13 @@ New features
`#233 <https://github.com/sphinx-gallery/sphinx-gallery/pull/233>`_ and
`#234 <https://github.com/sphinx-gallery/sphinx-gallery/pull/234>`_

Bug Fixes
'''''''''

* Reset ``sys.argv`` before running each example. See
`#252 <https://github.com/sphinx-gallery/sphinx-gallery/pull/252>`_
for more details.

v0.1.11
-------

Expand Down
15 changes: 15 additions & 0 deletions examples/plot_sys_argv.py
@@ -0,0 +1,15 @@
"""
Using ``sys.argv`` in examples
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to be an RST heading

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

==============================

Note that your example will be run by sphinx-gallery without arguments.
"""

import argparse
import sys

parser = argparse.ArgumentParser(description='Toy parser')
parser.add_argument('--option', default='default',
help='a dummy optional argument')
print('sys.argv:', sys.argv)
print('parsed args:', parser.parse_args())
10 changes: 10 additions & 0 deletions sphinx_gallery/gen_rst.py
Expand Up @@ -565,6 +565,15 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
time_elapsed = 0
block_vars = {'execute_script': execute_script, 'fig_count': 0,
'image_path': image_path_template, 'src_file': src_file}

argv_orig = sys.argv[:]
if block_vars['execute_script']:
# We want to run the example without arguments. See
# https://github.com/sphinx-gallery/sphinx-gallery/pull/252
# for more details.
sys.argv[0] = src_file
sys.argv[1:] = []

for blabel, bcontent in script_blocks:
if blabel == 'code':
code_output, rtime = execute_code_block(src_file, bcontent,
Expand All @@ -586,6 +595,7 @@ def generate_file_rst(fname, target_dir, src_dir, gallery_conf):
else:
example_rst += bcontent + '\n\n'

sys.argv = argv_orig
clean_modules()

# Writes md5 checksum if example has build correctly
Expand Down