输入函数时Python代码不起作用

时间:2014-09-24 19:00:09

标签: python function

我是Python的新手,我正在处理一些tar文件。以下示例有效:

#!/usr/bin/python
import os, readline, tarfile, scipy.io, numpy as np, sys
year = 2012;
month = 12;
day = 10;
RS = 9;
hour = 00;
minute = 05;
seconds = 00;
UTC = 1355094300;
anArchive = '/Users/user/data/20121210.zip';
tar = tarfile.open(anArchive);
dynamicPath = './%4d%2d%2d/RS%02d/%02d%02d%02d_%10d/all.txt' %(year, month, day, RS, hour,minute, seconds, UTC);
print(dynamicPath);
memb = tar.getmember(dynamicPath);
file = tar.extractfile(memb.name);
print('loading file with measurements...\n');
contents = file.read();
destinationFile = open("extractedFile.txt", "w");
destinationFile.write(contents);

从tar获取文件,提取它并将其写入新文件。

现在我想定义一个完全相同的函数:

#!/usr/bin/python
import os, readline, tarfile, scipy.io, numpy as np, sys
def extractFile():
    year = 2012;
    month = 12;
    day = 10;
    RS = 9;
    hour = 00;
    minute = 05;
    seconds = 00;
    UTC = 1355094300;
    anArchive = "/Users/user/data/20121210.zip";
    tar = tarfile.open(anArchive);
    dynamicPath = "./%4d%2d%2d/LOSS_RS%02d/%02d%02d%02d_%10d/all.txt" %(year, month, day, RS, hour,minute, seconds, UTC);
    print(dynamicPath);
    #memb = tar.getmember("./20121210/RS09/004501_1355096701/all.txt");
    memb = tar.getmember(dynamicPath);
    file = tar.extractfile(memb.name);
    print('loading file with measurements...\n');
    contents = file.read();
    destinationFile = open("extractedFile.txt", "w");
    destinationFile.write(contents);
    return

我保存并确保它是可执行文件后,我从终端执行它,同时检查缩进错误:

python -t extractFile.py

,结果一无所获。没有错误,执行"完成"但没有结果,就像我执行了空代码一样。

任何想法为什么相同的代码在用作函数时都不起作用?

1 个答案:

答案 0 :(得分:4)

您需要调用函数才能执行它 - 将此行添加到文件的末尾:

extractFile()

即。整个代码应该是:

#!/usr/bin/python
import os, readline, tarfile, scipy.io, numpy as np, sys
def extractFile():
    year = 2012;
    month = 12;
    day = 10;
    RS = 9;
    hour = 00;
    minute = 05;
    seconds = 00;
    UTC = 1355094300;
    anArchive = "/Users/user/data/20121210.zip";
    tar = tarfile.open(anArchive);
    dynamicPath = "./%4d%2d%2d/LOSS_RS%02d/%02d%02d%02d_%10d/all.txt" %(year, month, day, RS, hour,minute, seconds, UTC);
    print(dynamicPath);
    #memb = tar.getmember("./20121210/RS09/004501_1355096701/all.txt");
    memb = tar.getmember(dynamicPath);
    file = tar.extractfile(memb.name);
    print('loading file with measurements...\n');
    contents = file.read();
    destinationFile = open("extractedFile.txt", "w");
    destinationFile.write(contents);
    return
extractFile()