Errno 13 Permission denied. in jupyter notebook, UBUNTU - python

I'm newly using 'UBUNTU in windows' and opened jupyter notebook inside UBUNTU, make new python3 file and try to load a file named 'Elliptic_main.py'. However, the following code
%load Elliptic_main.py
gives error messages
---------------------------------------------------------------------------
PermissionError Traceback (most recent call last)
<ipython-input-1-69cbacf526f9> in <module>()
----> 1 get_ipython().run_line_magic('load', 'Elliptic_main.py')
~/.local/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
2129 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2130 with self.builtin_trap:
-> 2131 result = fn(*args,**kwargs)
2132 return result
2133
<decorator-gen-47> in load(self, arg_s)
~/.local/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/.local/lib/python3.6/site-packages/IPython/core/magics/code.py in load(self, arg_s)
333 search_ns = 'n' in opts
334
--> 335 contents = self.shell.find_user_code(args, search_ns=search_ns)
336
337 if 's' in opts:
~/.local/lib/python3.6/site-packages/IPython/core/interactiveshell.py in find_user_code(self, target, raw, py_only, skip_encoding_cookie, search_ns)
3263 if os.path.isfile(tgt): # Read file
3264 try :
-> 3265 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3266 except UnicodeDecodeError :
3267 if not py_only :
~/.local/lib/python3.6/site-packages/IPython/utils/openpy.py in read_py_file(filename, skip_encoding_cookie)
74 A unicode string containing the contents of the file.
75 """
---> 76 with open(filename) as f: # the open function defined in this module.
77 if skip_encoding_cookie:
78 return "".join(strip_encoding_cookie(f))
~/anaconda3/lib/python3.6/tokenize.py in open(filename)
450 detect_encoding().
451 """
--> 452 buffer = _builtin_open(filename, 'rb')
453 try:
454 encoding, lines = detect_encoding(buffer.readline)
PermissionError: [Errno 13] Permission denied: 'Elliptic_main.py'
I think this is an issue for UBUNTU, but I'm not sure. Anyone has same issue? Thanks for any helps
typing
ls -l Elliptic_main.py
gives the following message:
---------- 1 sungha sungha 1418 Sep 14 13:54 Elliptic_main.py
here sungha is my user name.

From the ls output
---------- 1 sungha sungha 1418 Sep 14 13:54 Elliptic_main.py
Notice the
----------
part that shows which permissions are set (see for example in this wiki for further details)
In your case you don't have ANY permissions on that file which is why you see Permission error
Try
chmod 600 # in case sungha is your username
chmod 666 # otherwise
Check the manpage of chmod by typing man chmod in your terminal for further details on what the difference is between the two

Related

OSError while calling Detectron2LayoutModel

After successfully installing Layout Parser in Windows, getting the below OS Error.
Code Used:
model = lp.Detectron2LayoutModel(config_path="lp://PubLayNet/mask_rcnn_X_101_32x8d_FPN_3x/config",
extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8],
label_map={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"})
Using layout parser, trying to extract the content from image. But when I try to load models in Layout parser, it fails with the below error
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_178664\3254664512.py in <module>
1 model = lp.Detectron2LayoutModel(config_path="lp://PubLayNet/mask_rcnn_X_101_32x8d_FPN_3x/config",
2 extra_config=["MODEL.ROI_HEADS.SCORE_THRESH_TEST", 0.8],
----> 3 label_map={0: "Text", 1: "Title", 2: "List", 3:"Table", 4:"Figure"})
4 # Load the deep layout model from the layoutparser API
5 # For all the supported model, please check the Model
~\Anaconda3\envs\layout\lib\site-packages\layoutparser\models\detectron2\layoutmodel.py in __init__(self, config_path, model_path, label_map, extra_config, enforce_cpu, device)
89 config_path, model_path, allow_empty_path=True
90 )
---> 91 config_path = PathManager.get_local_path(config_path)
92
93 if label_map is None:
~\Anaconda3\envs\layout\lib\site-packages\iopath\common\file_io.py in get_local_path(self, path, force, **kwargs)
1195 handler = self.__get_path_handler(path) # type: ignore
1196 try:
-> 1197 bret = handler._get_local_path(path, force=force, **kwargs)
1198 except TypeError:
1199 bret = handler._get_local_path(path, **kwargs)
~\Anaconda3\envs\layout\lib\site-packages\layoutparser\models\detectron2\catalog.py in _get_local_path(self, path, **kwargs)
134 else:
135 raise ValueError(f"Unknown data_type {data_type}")
--> 136 return PathManager.get_local_path(model_url, **kwargs)
137
138 def _open(self, path, mode="r", **kwargs):
~\Anaconda3\envs\layout\lib\site-packages\iopath\common\file_io.py in get_local_path(self, path, force, **kwargs)
1195 handler = self.__get_path_handler(path) # type: ignore
1196 try:
-> 1197 bret = handler._get_local_path(path, force=force, **kwargs)
1198 except TypeError:
1199 bret = handler._get_local_path(path, **kwargs)
~\Anaconda3\envs\layout\lib\site-packages\iopath\common\file_io.py in _get_local_path(self, path, force, cache_dir, **kwargs)
792
793 cached = os.path.join(dirname, filename)
--> 794 with file_lock(cached):
795 if not os.path.isfile(cached):
796 logger.info("Downloading {} ...".format(path))
~\Anaconda3\envs\layout\lib\site-packages\portalocker\utils.py in __enter__(self)
155
156 def __enter__(self):
--> 157 return self.acquire()
158
159 def __exit__(self,
~\Anaconda3\envs\layout\lib\site-packages\portalocker\utils.py in acquire(self, timeout, check_interval, fail_when_locked)
237
238 # Get a new filehandler
--> 239 fh = self._get_fh()
240
241 def try_close(): # pragma: no cover
~\Anaconda3\envs\layout\lib\site-packages\portalocker\utils.py in _get_fh(self)
287 def _get_fh(self) -> typing.IO:
288 '''Get a new filehandle'''
--> 289 return open(self.filename, self.mode, **self.file_open_kwargs)
290
291 def _get_lock(self, fh: typing.IO) -> typing.IO:
OSError: [Errno 22] Invalid argument: 'C:\\Users\\vchinna/.torch/iopath_cache\\s/nau5ut6zgthunil\\config.yaml?dl=1.lock'
Not sure whether it is a kind of lock or something.
Please help
Even I got a similar error. I tried out manually some work around in Windows.
I am using your case as example: OSError: [Errno 22] Invalid argument: 'C:\Users\vchinna/.torch/iopath_cache\s/nau5ut6zgthunil\config.yaml?dl=1.lock'
Please follow the following process.
Navigate to C:\Users\vchinna/.torch/iopath_cache\s/nau5ut6zgthunil\config.yaml
Open that config.yaml file
Scroll down to WEIGHTS: https://www.dropbox.com/s/h7th27jfv19rxiy/model_final.pth?dl=1 should be around 265 line.
Copy that link and paste it in your browser, a 'model_final.pth' will be downloaded. Copy this file to your desired folder.
Now replace the path to WEIGHTS: your_desired_folder/model_final.pth
Save it and run the code it works!
But there is a small work around I think before you do this (if you have not done)
[iopath work around][1]
https://github.com/Layout-Parser/layout-parser/issues/15 (Github link to the issue)

py2neo: using cypher inline gives 404 error

I was following simple py2neo tutorial here: http://nicolewhite.github.io/neo4j-jupyter/hello-world.html
Everything worked fine, all the entries appear in the neo4j in-browser version, however when I try to run inline Cypher queries, I get a 404 error.
%%cypher
http://neo4j:password#localhost:7474/db/data/
MATCH (person:Person)-[:LIKES]->(drink:Drink)
RETURN person.name, drink.name, drink.calories
Here's the traceback:
Format: (http|https)://username:password#hostname:port/db/name
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
<ipython-input-12-de2d5705ff61> in <module>
----> 1 get_ipython().run_cell_magic('cypher', '', 'http://neo4j:password#localhost:7474/db/data/\nMATCH (person:Person)-[:LIKES]->(drink:Drink)\nRETURN person.name, drink.name, drink.calories\n')
~/.local/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2369 with self.builtin_trap:
2370 args = (magic_arg_s, cell)
-> 2371 result = fn(*args, **kwargs)
2372 return result
2373
<decorator-gen-127> in execute(self, line, cell, local_ns)
~/.local/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
<decorator-gen-126> in execute(self, line, cell, local_ns)
~/.local/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/.local/lib/python3.6/site-packages/cypher/magic.py in execute(self, line, cell, local_ns)
106 user_ns.update(local_ns)
107 parsed = parse("""{0}\n{1}""".format(line, cell), self)
--> 108 conn = Connection.get(parsed['as'] or parsed['uri'], parsed['as'])
109 first_word = parsed['cypher'].split(None, 1)[:1]
110 if first_word and first_word[0].lower() == 'persist':
~/.local/lib/python3.6/site-packages/cypher/connection.py in get(cls, descriptor, alias)
45 cls.current = conn
46 else:
---> 47 cls.current = Connection(descriptor, alias)
48 if cls.current:
49 return cls.current
~/.local/lib/python3.6/site-packages/cypher/connection.py in __init__(self, connect_str, alias)
24 gdb = GraphDatabase(self.connections[connect_str])
25 else:
---> 26 gdb = GraphDatabase(connect_str)
27 alias = alias or connect_str
28 except:
~/.local/lib/python3.6/site-packages/neo4jrestclient/client.py in __init__(self, url, username, password, cert_file, key_file)
81 response_json = response.json()
82 else:
---> 83 raise NotFoundError(response.status_code, "Unable get root")
84 if "data" in response_json and "management" in response_json:
85 response = Request(**self._auth).get(response_json["data"])
NotFoundError: Code [404]: Not Found. Nothing matches the given URI.
Unable get root
I tried checking if the URI works according to this answer here, and I get 404 error there too:
~$ curl -i --user neo4j:password http://localhost:7474/db/data/
HTTP/1.1 404 Not Found
Access-Control-Allow-Origin: *
Cache-Control: must-revalidate,no-cache,no-store
Content-Type: text/html;charset=iso-8859-1
Content-Length: 0
I tried setting the Graph option to include the link, but it didn't help:
graph = Graph("http://neo4j:password#localhost:7474/db/data/")
Could you please tell me where have I made a mistake?
I am using py2neo most of the time. Here is how I connect to my local neo4j db.
from py2neo import Graph
graph = Graph("bolt://localhost:7687", auth=("neo4j", "xxxxx"))
try:
graph.run("Match () Return 1 Limit 1")
print('ok')
except Exception:
print('not ok')

Not sure why my build_image_data.py script for tensforflow isn't working

I'm trying to convert a set of jpg images to TFRecord for use with a CNN in Tensorflow.I'm using the script build_image_data.py from here:
https://github.com/tensorflow/models/blob/master/inception/inception/data/build_image_data.py
I've created a validation directory and a training directory as well as a labels.txt file with the appropriate labels. I run the script using jupyter notebook (I've also tried via command line) and I have changed the tf.app.flags.DEFINE_string arguments to the appropriate directory/file names. When I run it I get the following error:
Saving results to /tmp/
Determining list of input files and labels from /tmp/.
---------------------------------------------------------------------------
NotFoundError Traceback (most recent call last)
<ipython-input-2-6349ff3421a2> in <module>()
356
357 if __name__ == '__main__':
--> 358 tf.app.run()
C:\Users\Lenovo\Anaconda3\envs\tensorflow3_5\lib\site-packages\tensorflow\python\platform\app.py in run(main, argv)
42 # Call the main function, passing through any arguments
43 # to the final program.
---> 44 _sys.exit(main(_sys.argv[:1] + flags_passthrough))
45
46
<ipython-input-2-6349ff3421a2> in main(unused_argv)
350 # Run it!
351 _process_dataset('validation', FLAGS.validation_directory,
--> 352 FLAGS.validation_shards, FLAGS.labels_file)
353 _process_dataset('train', FLAGS.train_directory,
354 FLAGS.train_shards, FLAGS.labels_file)
<ipython-input-2-6349ff3421a2> in _process_dataset(name, directory, num_shards, labels_file)
336 labels_file: string, path to the labels file.
337 """
--> 338 filenames, texts, labels = _find_image_files(directory, labels_file)
339 _process_image_files(name, filenames, texts, labels, num_shards)
340
<ipython-input-2-6349ff3421a2> in _find_image_files(data_dir, labels_file)
288 print('Determining list of input files and labels from %s.' % data_dir)
289 unique_labels = [l.strip() for l in tf.gfile.FastGFile(
--> 290 labels_file, 'r').readlines()]
291
292 labels = []
C:\Users\Lenovo\Anaconda3\envs\tensorflow3_5\lib\site-packages\tensorflow\python\lib\io\file_io.py in readlines(self)
126 def readlines(self):
127 """Returns all lines from the file in a list."""
--> 128 self._preread_check()
129 lines = []
130 while True:
C:\Users\Lenovo\Anaconda3\envs\tensorflow3_5\lib\site-packages\tensorflow\python\lib\io\file_io.py in _preread_check(self)
71 with errors.raise_exception_on_not_ok_status() as status:
72 self._read_buf = pywrap_tensorflow.CreateBufferedInputStream(
---> 73 compat.as_bytes(self.__name), 1024 * 512, status)
74
75 def _prewrite_check(self):
C:\Users\Lenovo\Anaconda3\envs\tensorflow3_5\lib\contextlib.py in __exit__(self, type, value, traceback)
64 if type is None:
65 try:
---> 66 next(self.gen)
67 except StopIteration:
68 return
C:\Users\Lenovo\Anaconda3\envs\tensorflow3_5\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
464 None, None,
465 compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466 pywrap_tensorflow.TF_GetCode(status))
467 finally:
468 pywrap_tensorflow.TF_DeleteStatus(status)
NotFoundError: NewRandomAccessFile failed to Create/Open: : The system cannot find the path specified.
Any clues? I'm running the script from the same directory that contains my validation and training folders. Thanks.
EDIT: Tried using full path but still coming up with the same error. Here is the relevant section of code, I'm sure it's some simple error on my part.
tf.app.flags.DEFINE_string('train_directory', '/tmp/',
'C:/Users/Lenovo/dir2/tensorflow_code/cell_tf/cell_images/main_cell_images/TRAIN_DIR')
tf.app.flags.DEFINE_string('validation_directory', '/tmp/',
'C:/Users/Lenovo/dir2/tensorflow_code/cell_tf/cell_images/main_cell_images/VALIDATION_DIR')
tf.app.flags.DEFINE_string('output_directory', '/tmp/',
'C:/Users/Lenovo/dir2/tensorflow_code/cell_tf/cell_images/main_cell_images/OUTPUT_DIR')
tf.app.flags.DEFINE_integer('train_shards', 1,
'Number of shards in training TFRecord files.')
tf.app.flags.DEFINE_integer('validation_shards', 1,
'Number of shards in validation TFRecord files.')
tf.app.flags.DEFINE_integer('num_threads', 1,
'Number of threads to preprocess the images.')
tf.app.flags.DEFINE_string('labels_file', '','C:/Users/Lenovo/dir2/tensorflow_code/cell_tf/cell_images/main_cell_images/MYLABELS.TXT')
You should put the address in place of /temp/
tf.app.flags.DEFINE_string('train_directory', 'D:/full/path',
'Training data directory')

Using Sacred Module with iPython

I am trying to set up sacred for Python and I am going through the tutorial. I was able to set up sacred using pip install sacred with no issues. I am having trouble running the basic code:
from sacred import Experiment
ex = Experiment("hello_world")
Running this code returns the a ValueError:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-25-66f549cfb192> in <module>()
1 from sacred import Experiment
2
----> 3 ex = Experiment("hello_world")
/Users/ryandevera/anaconda/lib/python2.7/site-packages/sacred/experiment.pyc in __init__(self, name, ingredients)
42 super(Experiment, self).__init__(path=name,
43 ingredients=ingredients,
---> 44 _caller_globals=caller_globals)
45 self.default_command = ""
46 self.command(print_config, unobserved=True)
/Users/ryandevera/anaconda/lib/python2.7/site-packages/sacred/ingredient.pyc in __init__(self, path, ingredients, _caller_globals)
48 self.doc = _caller_globals.get('__doc__', "")
49 self.sources, self.dependencies = \
---> 50 gather_sources_and_dependencies(_caller_globals)
51
52 # =========================== Decorators ==================================
/Users/ryandevera/anaconda/lib/python2.7/site-packages/sacred/dependencies.pyc in gather_sources_and_dependencies(globs)
204 def gather_sources_and_dependencies(globs):
205 dependencies = set()
--> 206 main = Source.create(globs.get('__file__'))
207 sources = {main}
208 experiment_path = os.path.dirname(main.filename)
/Users/ryandevera/anaconda/lib/python2.7/site-packages/sacred/dependencies.pyc in create(filename)
61 if not filename or not os.path.exists(filename):
62 raise ValueError('invalid filename or file not found "{}"'
---> 63 .format(filename))
64
65 mainfile = get_py_file_if_possible(os.path.abspath(filename))
ValueError: invalid filename or file not found "None"
I am not sure why this error is returning. The documentation does not say anything about setting up an Experiment file prior to running the code. Any help would be greatly appreciated!
The traceback given indicates that the constructor for Experiment searches its namespace to find the file in which its defined.
Thus, to make the example work, place the example code into a file and run that file directly.
If you are using ipython, then you could always try using the %%python command, which will effectively capture the code you give it into a file before running it (in a separate python process).
According to the docs, if you're in IPython/Jupyter, you can allow the Experiment to run in a non-reproducible interactive environment:
ex = Experiment('jupyter_ex', interactive=True)
https://sacred.readthedocs.io/en/latest/experiment.html#run-the-experiment
The docs say it nicely (TL;DR: sacred checks this for you and fails in order to warn you)
Warning
By default, Sacred experiments will fail if run in an interactive
environment like a REPL or a Jupyter Notebook. This is an intended
security measure since in these environments reproducibility cannot be
ensured. If needed, this safeguard can be deactivated by passing
interactive=True to the experiment like this:
ex = Experiment('jupyter_ex', interactive=True)
Setting interactive=True doesn't work if you run the notebook as a script through ipython.
$ ipython code.ipynb
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Cell In[1], line 1
----> 1 ex = Experiment("image_classification", interactive=True)
2 ex.observers.append(NeptuneObserver(run=neptune_run))
File ~\miniconda3\envs\py38\lib\site-packages\sacred\experiment.py:119, in Experiment.__init__(self, name, ingredients, interactive, base_dir, additional_host_info, additional_cli_options, save_git_info)
117 elif name.endswith(".pyc"):
118 name = name[:-4]
--> 119 super().__init__(
120 path=name,
121 ingredients=ingredients,
122 interactive=interactive,
123 base_dir=base_dir,
124 _caller_globals=caller_globals,
125 save_git_info=save_git_info,
126 )
127 self.default_command = None
128 self.command(print_config, unobserved=True)
File ~\miniconda3\envs\py38\lib\site-packages\sacred\ingredient.py:75, in Ingredient.__init__(self, path, ingredients, interactive, _caller_globals, base_dir, save_git_info)
69 self.save_git_info = save_git_info
70 self.doc = _caller_globals.get("__doc__", "")
71 (
72 self.mainfile,
73 self.sources,
74 self.dependencies,
---> 75 ) = gather_sources_and_dependencies(
76 _caller_globals, save_git_info, self.base_dir
77 )
78 if self.mainfile is None and not interactive:
79 raise RuntimeError(
80 "Defining an experiment in interactive mode! "
81 "The sourcecode cannot be stored and the "
82 "experiment won't be reproducible. If you still"
83 " want to run it pass interactive=True"
84 )
File ~\miniconda3\envs\py38\lib\site-packages\sacred\dependencies.py:725, in gather_sources_and_dependencies(globs, save_git_info, base_dir)
723 def gather_sources_and_dependencies(globs, save_git_info, base_dir=None):
724 """Scan the given globals for modules and return them as dependencies."""
--> 725 experiment_path, main = get_main_file(globs, save_git_info)
727 base_dir = base_dir or experiment_path
729 gather_sources = source_discovery_strategies[SETTINGS["DISCOVER_SOURCES"]]
File ~\miniconda3\envs\py38\lib\site-packages\sacred\dependencies.py:596, in get_main_file(globs, save_git_info)
594 main = None
595 else:
--> 596 main = Source.create(globs.get("__file__"), save_git_info)
461 return Source(main_file, get_digest(main_file), repo, commit, is_dirty)
File ~\miniconda3\envs\py38\lib\site-packages\sacred\dependencies.py:382, in get_py_file_if_possible(pyc_name)
380 if pyc_name.endswith((".py", ".so", ".pyd")):
381 return pyc_name
--> 382 assert pyc_name.endswith(".pyc")
383 non_compiled_file = pyc_name[:-1]
384 if os.path.exists(non_compiled_file):
sacred==0.8.2

run python manage.py shell occurs errors

E:\Users\liuzhijun\workspace\mysite>python manage.py shell
---------------------------------------------------------------------------
TypeError Python 2.7.4: E:\Python27\python.exe
Mon May 20 07:22:35 2013
A problem occured executing Python code. Here is the sequence of function
calls leading up to the error, with the most recent (innermost) call last.
E:\Users\liuzhijun\workspace\mysite\manage.py in ()
7 #!/usr/bin/env python
8 import os
9 import sys
---> 10
global execute_from_command_line = <function execute_from_command_line at 0x02AF94F0>
global sys.argv = ['manage.py', 'shell']
11 if __name__ == "__main__":
12 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
13
14 from django.core.management import execute_from_command_line
15
16 execute_from_command_line(sys.argv)
17
E:\Python27\lib\site-packages\django\core\management__init__.pyc in execute_from_command_line(argv=['manage.py', 'shell'])
428 )
429
430 # Import the project module. We add the parent directory to PYTHONPATH to
431 # avoid some of the path errors new users can have.
432 sys.path.append(os.path.join(project_directory, os.pardir))
433 import_module(project_name)
434 sys.path.pop()
435
436 return project_directory
437
438 def execute_from_command_line(argv=None):
439 """
440 A simple method that runs a ManagementUtility.
441 """
442 utility = ManagementUtility(argv)
--> 443 utility.execute()
444
445 def execute_manager(settings_mod, argv=None):
446 """
447 Like execute_from_command_line(), but for use by manage.py, a
448 project-specific django-admin.py utility.
449 """
450 warnings.warn(
451 "The 'execute_manager' function is deprecated, "
452 "you likely need to update your 'manage.py'; "
453 "please see the Django 1.4 release notes "
454 "(https://docs.djangoproject.com/en/dev/releases/1.4/).",
455 PendingDeprecationWarning)
456
457 setup_environ(settings_mod)
458 utility = ManagementUtility(argv)
......omit lots of codes......
update:
E:\Python27\lib\site-packages\django\core\management__init__.pyc in execute(self=)
367 elif args[2] == '--commands':
368 sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
369 else:
370 self.fetch_command(args[2]).print_help(self.prog_name, args[2])
371 elif subcommand == 'version':
372 sys.stdout.write(parser.get_version() + '\n')
373 # Special-cases: We want 'django-admin.py --version' and
374 # 'django-admin.py --help' to work, for backwards compatibility.
375 elif self.argv[1:] == ['--version']:
376 # LaxOptionParser already takes care of printing the version.
377 pass
378 elif self.argv[1:] in (['--help'], ['-h']):
379 parser.print_lax_help()
380 sys.stdout.write(self.main_help_text() + '\n')
381 else:
--> 382 self.fetch_command(subcommand).run_from_argv(self.argv)
383
384 def setup_environ(settings_mod, original_settings_path=None):
385 """
386 Configures the runtime environment. This can also be used by external
387 scripts wanting to set up a similar environment to manage.py.
388 Returns the project directory (assuming the passed settings module is
389 directly in the project directory).
390
391 The "original_settings_path" parameter is optional, but recommended, since
392 trying to work out the original path from the module can be problematic.
393 """
394 warnings.warn(
395 "The 'setup_environ' function is deprecated, "
396 "you likely need to update your 'manage.py'; "
397 "please see the Django 1.4 release notes "
E:\Python27\lib\site-packages\django\core\management\base.pyc in run_from_argv(self=, argv=['manage.py', 'shell'])
181 ``self.usage()``.
182
183 """
184 parser = self.create_parser(prog_name, subcommand)
185 parser.print_help()
186
187 def run_from_argv(self, argv):
188 """
189 Set up any environment changes requested (e.g., Python path
190 and Django settings), then run this command.
191
192 """
193 parser = self.create_parser(argv[0], argv[1])
194 options, args = parser.parse_args(argv[2:])
195 handle_default_options(options)
--> 196 self.execute(*args, **options.__dict__)
global s = undefined
global appname = undefined
global appname...c = undefined
197
198 def execute(self, *args, **options):
199 """
200 Try to execute this command, performing model validation if
201 needed (as controlled by the attribute
202 ``self.requires_model_validation``). If the command raises a
203 ``CommandError``, intercept it and print it sensibly to
204 stderr.
205 """
206 show_traceback = options.get('traceback', False)
207
208 # Switch to English, because django-admin.py creates database content
209 # like permissions, and those shouldn't contain any translations.
210 # But only do this if we can assume we have a working settings file,
211 # because django.utils.translation requires settings.
E:\Python27\lib\site-packages\django\core\management\base.pyc in execute(self=, *args=(), **options={'plain': None, 'pythonpath': None, 'settings': None, 'traceback': None, 'verbosity':'1'})
217 translation.activate('en-us')
218 except ImportError, e:
219 # If settings should be available, but aren't,
220 # raise the error and quit.
221 if show_traceback:
222 traceback.print_exc()
223 else:
224 sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
225 sys.exit(1)
226
227 try:
228 self.stdout = options.get('stdout', sys.stdout)
229 self.stderr = options.get('stderr', sys.stderr)
230 if self.requires_model_validation:
231 self.validate()
--> 232 output = self.handle(*args, **options)
global Rather = undefined
global than = undefined
global implementing = undefined
global handle = undefined
global subclasses = undefined
global must = undefined
global implement = undefined
233 if output:
234 if self.output_transaction:
235 # This needs to be imported here, because it relies on
236 # settings.
237 from django.db import connections, DEFAULT_DB_ALIAS
238 connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
239 if connection.ops.start_transaction_sql():
240 self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()) + '\n')
241 self.stdout.write(output)
242 if self.output_transaction:
243 self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
244 except CommandError, e:
245 if show_traceback:
246 traceback.print_exc()
247 else:
E:\Python27\lib\site-packages\django\core\management\base.pyc in handle(self=, *args=(), **options={'plain': None, 'pythonpath': None, 'settings': None, 'traceback': None, 'verbosity': '1'})
356 """
357 A command which takes no arguments on the command line.
358
359 Rather than implementing ``handle()``, subclasses must implement
360 ``handle_noargs()``; ``handle()`` itself is overridden to ensure
361 no arguments are passed to the command.
362
363 Attempting to pass arguments will raise ``CommandError``.
364
365 """
366 args = ''
367
368 def handle(self, *args, **options):
369 if args:
370 raise CommandError("Command doesn't accept any arguments")
--> 371 return self.handle_noargs(**options)
372
373 def handle_noargs(self, **options):
374 """
375 Perform this command's actions.
376
377 """
378 raise NotImplementedError()
379
380
381
382
383
384
385
386
E:\Python27\lib\site-packages\django\core\management\commands\shell.pyc in handle_noargs(self=, **options={'plain': None, 'pythonpath': None, 'settings': None, 'traceback': None, 'verbos
ity': '1'})
39 pass
40 raise ImportError
41
42 def handle_noargs(self, **options):
43 # XXX: (Temporary) workaround for ticket #1796: force early loading of all
44 # models from installed apps.
45 from django.db.models.loading import get_models
46 get_models()
47
48 use_plain = options.get('plain', False)
49
50 try:
51 if use_plain:
52 # Don't bother loading IPython, because the user wants plain Python.
53 raise ImportError
---> 54 self.run_shell()
55 except ImportError:
56 import code
57 # Set up a dictionary to serve as the environment for the shell, so
58 # that tab completion works on objects that are imported at runtime.
59 # See ticket 5082.
60 imported_objects = {}
61 try: # Try activating rlcompleter, because it's handy.
62 import readline
63 except ImportError:
64 pass
65 else:
66 # We don't have to wrap the following import in a 'try', because
67 # we already know 'readline' was imported successfully.
68 import rlcompleter
69 readline.set_completer(rlcompleter.Completer(imported_objects).complete)
E:\Python27\lib\site-packages\django\core\management\commands\shell.pyc in run_shell(self=)
22 try:
23 from IPython.Shell import IPShell
24 shell = IPShell(argv=[])
25 shell.mainloop()
26 except ImportError:
27 # IPython not found at all, raise ImportError
28 raise
29
30 def bpython(self):
31 import bpython
32 bpython.embed()
33
34 def run_shell(self):
35 for shell in self.shells:
36 try:
---> 37 return getattr(self, shell)()
global t = undefined
global __name__t = undefined
38 except ImportError:
39 pass
40 raise ImportError
41
42 def handle_noargs(self, **options):
43 # XXX: (Temporary) workaround for ticket #1796: force early loading of all
44 # models from installed apps.
45 from django.db.models.loading import get_models
46 get_models()
47
48 use_plain = options.get('plain', False)
49
50 try:
51 if use_plain:
52 # Don't bother loading IPython, because the user wants plain Python.
E:\Python27\lib\site-packages\django\core\management\commands\shell.pyc in ipython(self=)
9 )
10 help = "Runs a Python interactive interpreter. Tries to use IPython, if it's available."
11 shells = ['ipython', 'bpython']
12 requires_model_validation = False
13
14 def ipython(self):
15 try:
16 from IPython import embed
17 embed()
18 except ImportError:
19 # IPython < 0.11
20 # Explicitly pass an empty list as arguments, because otherwise
21 # IPython would use sys.argv from this script.
22 try:
23 from IPython.Shell import IPShell
---> 24 shell = IPShell(argv=[])
global j = undefined
global d = undefined
global s = undefined
global t = undefined
25 shell.mainloop()
26 except ImportError:
27 # IPython not found at all, raise ImportError
28 raise
29
30 def bpython(self):
31 import bpython
32 bpython.embed()
33
34 def run_shell(self):
35 for shell in self.shells:
36 try:
37 return getattr(self, shell)()
38 except ImportError:
39 pass
E:\Python27\lib\site-packages\IPython\Shell.pyc in init(self=, argv=[], user_ns=None, user_global_ns=None, debug=1, shell_class=)
58 # Default timeout for waiting for multithreaded shells (in seconds)
59 GUI_TIMEOUT = 10
60
61 #-----------------------------------------------------------------------------
62 # This class is trivial now, but I want to have it in to publish a clean
63 # interface. Later when the internals are reorganized, code that uses this
64 # shouldn't have to change.
65
66 class IPShell:
67 """Create an IPython instance."""
68
69 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
70 debug=1,shell_class=InteractiveShell):
71 self.IP = make_IPython(argv,user_ns=user_ns,
72 user_global_ns=user_global_ns,
---> 73 debug=debug,shell_class=shell_class)
global For = undefined
global more = undefined
global details = undefined
global see = undefined
global the = undefined
global __call__ = undefined
global method = undefined
global below. = undefined
74
75 def mainloop(self,sys_exit=0,banner=None):
76 self.IP.mainloop(banner)
77 if sys_exit:
78 sys.exit()
79
80 #-----------------------------------------------------------------------------
81 def kill_embedded(self,parameter_s=''):
82 """%kill_embedded : deactivate for good the current embedded IPython.
83
84 This function (after asking for confirmation) sets an internal flag so that
85 an embedded IPython will never activate again. This is useful to
86 permanently disable a shell that is being called inside a loop: once you've
87 figured out what you needed from it, you may then kill it and the program
88 will then continue to run without the interactive shell interfering again.
E:\Python27\lib\site-packages\IPython\ipmaker.pyc in make_IPython(argv=[], user_ns=None, user_global_ns=None, debug=1, rc_override=None, shell_class=, embedded=False, **kw={})
506 # tweaks. Basically options which affect other options. I guess this
507 # should just be written so that options are fully orthogonal and we
508 # wouldn't worry about this stuff!
509
510 if IP_rc.classic:
511 IP_rc.quick = 1
512 IP_rc.cache_size = 0
513 IP_rc.pprint = 0
514 IP_rc.prompt_in1 = '>>> '
515 IP_rc.prompt_in2 = '... '
516 IP_rc.prompt_out = ''
517 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
518 IP_rc.colors = 'NoColor'
519 IP_rc.xmode = 'Plain'
520
--> 521 IP.pre_config_initialization()
522 # configure readline
523
524 # update exception handlers with rc file status
525 otrap.trap_out() # I don't want these messages ever.
526 IP.magic_xmode(IP_rc.xmode)
527 otrap.release_out()
528
529 # activate logging if requested and not reloading a log
530 if IP_rc.logplay:
531 IP.magic_logstart(IP_rc.logplay + ' append')
532 elif IP_rc.logfile:
533 IP.magic_logstart(IP_rc.logfile)
534 elif IP_rc.log:
535 IP.magic_logstart()
536
E:\Python27\lib\site-packages\IPython\iplib.pyc in pre_config_initialization(self=)
820 self.user_ns, # globals
821 # Skip our own frame in searching for locals:
822 sys._getframe(depth+1).f_locals # locals
823 ))
824
825 def pre_config_initialization(self):
826 """Pre-configuration init method
827
828 This is called before the configuration files are processed to
829 prepare the services the config files might need.
830
831 self.rc already has reasonable default values at this point.
832 """
833 rc = self.rc
834 try:
--> 835 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
global prompt = undefined
global a = undefined
global string = <module 'string' from 'E:\Python27\lib\string.pyc'>
global to = undefined
global be = undefined
global printed = undefined
global the = undefined
global user. = undefined
836 except exceptions.UnicodeDecodeError:
837 print "Your ipythondir can't be decoded to unicode!"
838 print "Please set HOME environment variable to something that"
839 print r"only has ASCII characters, e.g. c:\home"
840 print "Now it is",rc.ipythondir
841 sys.exit()
842 self.shadowhist = IPython.history.ShadowHist(self.db)
843
844 def post_config_initialization(self):
845 """Post configuration init method
846
847 This is called after the configuration files have been processed to
848 'finalize' the initialization."""
849
850 rc = self.rc
E:\Python27\lib\site-packages\IPython\Extensions\pickleshare.pyc in init(self=PickleShareDB('C:\Users\liuzhijun_ipython\db'),root=u'C:\Users\liuzhijun\_ipython/db')
38 import cPickle as pickle
39 import UserDict
40 import warnings
41 import glob
42
43 def gethashfile(key):
44 return ("%02x" % abs(hash(key) % 256))[-2:]
45
46 _sentinel = object()
47
48 class PickleShareDB(UserDict.DictMixin):
49 """ The main 'connection' object for PickleShare database """
50 def __init__(self,root):
51 """ Return a db object that will manage the specied directory"""
52 self.root = Path(root).expanduser().abspath()
---> 53 if not self.root.isdir():
54 self.root.makedirs()
55 # cache has { 'key' : (obj, orig_mod_time) }
56 self.cache = {}
57
58
59 def __getitem__(self,key):
60 """ db['key'] reading """
61 fil = self.root / key
62 try:
63 mtime = (fil.stat()[stat.ST_MTIME])
64 except OSError:
65 raise KeyError(key)
66
67 if fil in self.cache and mtime == self.cache[fil][1]:
68 return self.cache[fil][0]
TypeError: _isdir() takes exactly 1 argument (0 given)
Oops, IPython crashed. We do our best to make it stable, but...
A crash report was automatically generated with the following information:
- A verbatim copy of the crash traceback.
- A copy of your input history during this session.
- Data on your current IPython configuration.
It was left in the file named:
'C:\Users\liuzhijun_ipython\IPython_crash_report.txt'
If you can email this file to the developers, the information in it will help
them in understanding and correcting the problem.
You can mail it to: Fernando Perez at fperez.net#gmail.com
with the subject 'IPython Crash Report'.
If you want to do it now, the following command will work (under Unix):
mail -s 'IPython Crash Report' fperez.net#gmail.com < C:\Users\liuzhijun_ipython\IPython_crash_report.txt
To ensure accurate tracking of this issue, please file a report about it at:
https://bugs.launchpad.net/ipython/+filebug
Press enter to exit:
system env:windows8

Categories