Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 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 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...