2017-02-25 3 views
0

Eclipse에서 PyDev를 사용하고 "AttributeError : 'Namespace'객체를 수신하면 'perfect4k'속성이 없습니다. 그림은 프로젝트 폴더 아래에 저장되지만 가능한 것은 아닌 것처럼 보입니다. .로드 사전에 감사, 파이썬에서 뉴비입니다 참고로,이 내가 인터넷을 빌려 예제 코드Python에서 Argparse로 그림로드 중 오류가 발생했습니다.

import numpy as np 
from PIL import Image 
import time 
from mazes import Maze 
from factory import SolverFactory 

# Read command line arguments - the python argparse class is convenient here. 
import argparse 
sf = SolverFactory() 
parser = argparse.ArgumentParser() 
parser.add_argument("-m", "--method", nargs='?', const=sf.Default, default=sf.Default, 
         choices=sf.Choices) 
parser.add_argument("perfect4k.png", help="4kImage", default=None, nargs='?') #input_file 
parser.add_argument("SaveM.png", help="4kImageSave", default=None, nargs='?') #output_file 
args = parser.parse_args() 

method = args.method 

# Load Image 
print ("Loading Image") 
im = Image.open(args.perfect4k.png) #args.input_file 

# Create the maze (and time it) - for many mazes this is more time consuming than solving the maze 
print ("Creating Maze") 
t0 = time.time() 
maze = Maze(im) 
t1 = time.time() 
print ("Node Count:", maze.count) 
total = t1-t0 
print ("Time elapsed:", total, "\n") 

# Create and run solver 
[title, solver] = sf.createsolver(args.method) 
print ("Starting Solve:", title) 

t0 = time.time() 
[result, stats] = solver(maze) 
t1 = time.time() 

total = t1-t0 

# Print solve stats 
print ("Nodes explored: ", stats[0]) 
if (stats[2]): 
    print ("Path found, length", stats[1]) 
else: 
    print ("No Path Found") 
print ("Time elapsed: ", total, "\n") 

""" 
Create and save the output image. 
This is simple drawing code that travels between each node in turn, drawing either 
a horizontal or vertical line as required. Line colour is roughly interpolated between 
blue and red depending on how far down the path this section is. Dependency on numpy 
should be easy to remove at some point. 
""" 

print ("Saving Image") 
mazeimage = np.array(im) 
imout = np.array(mazeimage) 
imout[imout==1] = 255 
out = imout[:,:,np.newaxis] 

out = np.repeat(out, 3, axis=2) 

resultpath = [n.Position for n in result] 

length = len(resultpath) 

px = [0, 0, 0] 
for i in range(0, length - 1): 
    a = resultpath[i] 
    b = resultpath[i+1] 

    # Blue - red 
    px[0] = int((i/length) * 255) 
    px[2] = 255 - px[0] 

    if a[0] == b[0]: 
     # Ys equal - horizontal line 
     for x in range(min(a[1],b[1]), max(a[1],b[1])): 
      out[a[0],x,:] = px 
    elif a[1] == b[1]: 
     # Xs equal - vertical line 
     for y in range(min(a[0],b[0]), max(a[0],b[0]) + 1): 
      out[y,a[1],:] = px 

img = Image.fromarray(out) 
img.save(args.SaveM.png) #CHANGED 

출력 :..

pydev debugger: starting (pid: 12436) 
Traceback (most recent call last): 
    File "C:\Users\Gabriel\.p2\pool\plugins\org.python.pydev_5.5.0.201701191708\pysrc\pydevd.py", line 1537, in <module> 
Loading Image 
    globals = debugger.run(setup['file'], None, None, is_module) 
    File "C:\Users\Gabriel\.p2\pool\plugins\org.python.pydev_5.5.0.201701191708\pysrc\pydevd.py", line 976, in run 
    pydev_imports.execfile(file, globals, locals) # execute the script 
    File "C:\Users\Gabriel\.p2\pool\plugins\org.python.pydev_5.5.0.201701191708\pysrc\_pydev_imps\_pydev_execfile.py", line 25, in execfile 
    exec(compile(contents+"\n", file, 'exec'), glob, loc) 
    File "C:\Users\Gabriel\Desktop\AP Computer Science\PythonMaze\solve.py", line 21, in <module> 
    im = Image.open(args.perfect4k.png) #args.input_file 
AttributeError: 'Namespace' object has no attribute 'perfect4k' 
+0

구체적으로 무엇이 오류입니까 - 여기에 런타임 출력/스택 추적을 추가 할 수 있습니까? –

+0

@DannyStaple 출력을 추가하기 위해 게시물을 편집했습니다. 희망이 도움이 – E36

답변

0

파이썬 변수 이름이 포함될 수 없습니다 도트 "."문자를 사용합니다. 목적.

"perfect4k.png"라는 이름이 args 중 하나에 사용되며 argparse에 대한이 동작은 잘 정의 된 것으로 들리지 않습니다.

"_"대신 밑줄을 사용하는 것이 좋습니다. 도움말 텍스트에이 이름이 표시되기를 원하면 키워드 매개 변수 "metavar"를 사용해보십시오.

parser.add_argument("input_file", metavar="perfect4k.png", help="4kImage", 
    default=None, nargs='?') #input_file 

그래서 실제 인수가 "INPUT_FILE입니다 : 당신이이 방법을 추가 할 수 있습니다 특정 경우

:

metavar - A name for the argument in usage messages.

(https://docs.python.org/3/library/argparse.html#the-add-argument-method 참조 :)으로 파이썬 문서에 설명되어 있습니다 ", 도움말 출력에서"perfect4k.png "라고합니다.

이는 코드의 다른 곳에서도 input_file으로 참조해야 함을 의미합니다. 또한 출력 파일에 동일한 처리 방법을 제공해야합니다.

+0

고마워요! 이 문제가 해결되었습니다. – E36

+0

그렇다면 답을 표시 하시겠습니까? –

관련 문제