Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

cannot concatenate 'str' and 'file' objects : Python error

I have

Following piece of code:

for src_filename, src_code in src_dict.iteritems(): 
try:
set.dependencies = subprocess.check_output('unifdef -s /home/c/maindir/folder/' +src_filename, shell=True)
except subprocess.CalledProcessError, e:
       print "code is bad" +set.property
       set.bad = 1
       raise
set.dependencies = list(set(set.dependencies.splitlines()))

I wanted to un-hardcode the path so I wrote following piece of code:

filepath = os.path.join(maindirpath, "folder/")

maindir is argument here: /home/c/maindir

 path = open(filepath)
 set.dependencies = subprocess.check_output("unifdef" '-s' path +src_filename, shell=True)

It throws following error:

TypeError: cannot concatenate 'str' and 'file' objects

I am new to python. can anybody help, where I am getting wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
for src_file, src_code in src_dict.iteritems():

  # assuming, here, that you want to honor the handle's path if already given
  filename = src_file.name
  if not '/' in filename:
    filename = os.path.join(filepath, filename)

  try:
    set.dependencies = subprocess.check_output(['unifdef', '-s', filename])
  except subprocess.CalledProcessError:
    pass # etc.

By the way, set is a bad variable name, since set is also a Python data type; you're making the data type unusable in your code by shadowing it with a like-named variable. Don't do that!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...