2013-09-21 2 views
0

인터페이스 파일을 다시 쓰는 스크립트를 설정하려고합니다. 결국 정적으로 IP 주소가 변경되지만 실행하면 'new_location_interfaces'라는 줄에 오류가 발생합니다. truncate() '그리고 그것은'str '개체가 잘리지 않는다는 것을 말한다.파이썬 구문 잘림 오류

from sys import argv 
from os.path import exists 
import os 

script_name = argv 

print "You are currently running %s" % script_name 
print "Version: 0.1" 
print """Desciption: This script will change the IP address of the 
Raspberry Pi from dynamic to static. 
""" 
print "If you don\'t want to continue, hit CTRL-C (^C)." 
print "If you do want that, hit RETURN" 

raw_input("?") 

# Main code block 

text_to_copy = """ 
auto lo\n 
iface lo inet loopback 
iface etho inet dhcp\n 
allow-hotplug wlan0 
iface wlan0 inet manual 
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf 
iface default inet dhcp 
""" 

if exists("/etc/network/interfaces"): 
    print "\nFile exists." 
    interfaces_file = open("/etc/network/interfaces", 'w') 
    print "Truncating/erasing contents . ." 
    interfaces_file.truncate() 
    print "Writing contents . ." 
    interfaces_file.write(text_to_copy) 
    interfaces_file.close() 
else: 
    print "\nCould not find the \'interfaces\' file." 
    print "Please specify the location:", 
    new_location_interfaces = raw_input() 
    open(new_location_interfaces, 'w') 
    print "Truncating/erasing contents . ." 
    new_location_interfaces.truncate() 
    print "Writing contents . ." 
    new_location_interfaces.write(text_to_copy) 
    new_location_interfaces.close() 

나는 파이썬에 매우 익숙하며, 내 코드는 아마도 끔찍할 것이다. 그러나 어떤 도움을 주시면 감사하겠습니다.

답변

3

new_location_interfaces은 파일 개체가 아닙니다.

new_location_interfaces = raw_input() 

다음 줄의 open() 전화, 아무것도에 할당되지 않은 :

open(new_location_interfaces, 'w') 

이 아마도 당신이 객체 있음을 절단하고 싶었다는 문자열의 raw_input() 호출의 결과인가? 예를 들어

:

new_location_interfaces = raw_input() 
fh = open(new_location_interfaces, 'w') 
print "Truncating/erasing contents . ." 
fh.truncate() 
print "Writing contents . ." 
fh.write(text_to_copy) 
fh.close() 

그러나, 이미 파일을 자릅니다 (w로 설정 모드) 쓰기 위해 파일을 열고, 당신의 .truncate() 전화는 완전히 중복입니다.

+0

아 물론 알지 못했습니다! 결국 당신이 말한 것은 절단 된 선을 완전히 제거 할 수 있다는 것입니까? –

+0

@BobJones : 그렇습니다.'.truncate()'줄을 완전히 제거 할 수 있습니다. –