简体   繁体   English

为什么直接运行脚本不起作用,但是“ python script_name.py”起作用

[英]Why does directly run script not work but “python script_name.py” does

I wrote a script to scraping data from a site. 我编写了一个脚本,用于从站点抓取数据。 It works when I run it with "python script.py" but when chmod +x and run directly from shell, it not work properly (not overwrite the output file) 当我使用“ python script.py”运行它时,它可以工作,但是当chmod + x直接从shell运行时,它不能正常工作(不会覆盖输出文件)

here is my code (just try to use HTMLParser): 这是我的代码(只需尝试使用HTMLParser):

#!/usr/bin/env python


from HTMLParser import HTMLParser
import urllib
import codecs
import string

FILE_NAME = 'kq.txt'
LINK = 'http://kqxs.vn/'

class MyHTMLParser(HTMLParser):
    """Parser get content in first table in site"""
    def __init__(self):
        self.reset()
        self.fed = []
        self.found = False
        self.done = False
    def handle_starttag(self, tag, attrs):
        if tag == "table":
            self.found = True
        if tag == "/table":
            self.found = False

    def handle_endtag(self, tag):
        if tag == "table":
            self.done = True

    def handle_data(self, data):
        if self.found and not self.done:
            self.fed.append(data)

    def get_data(self):
        return self.fed

#read data from URL
response = urllib.urlopen(LINK)
#print response.headers['content-type']
html = response.read()

html = unicode(html, 'utf-8')

parser = MyHTMLParser()
parser.feed(html)

result = parser.get_data()
#write to file
fw = codecs.open(FILE_NAME, 'w', 'utf-8')
#line.strip() remove string contains only spaces
#[fw.write(line + '\n') for line in result if line.strip()]
fw.writelines(line + '\n' for line in result if line.strip())

fw.close()

print "Done! data printed to file %s" %(FILE_NAME)

Here is result from my shell 这是我的壳的结果

famihug@hvn:/home/famihug%~/bin/leecher.py; cat ~/bin/kq.txt                [0]
Done! data printed to file kq.txt
Giải đặc biệt
**92296** 


**(HERE I RUN IT FROM INSIDE VIM with !python %)**
famihug@hvn:/home/famihug/bin%vim leecher.py                                [0]

Done! data printed to file kq.txt

Press ENTER or type command to continue
zsh: suspended  vim leecher.py
famihug@hvn:/home/famihug/bin%cat kq.txt                                   [20]
Giải đặc biệt
****88705**** 

famihug@hvn:/home/famihug/bin%/usr/bin/env python                           [0]
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 

famihug@hvn:/home/famihug/bin%python                                        [0]
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 

The script still prints out last line Done! 该脚本仍会打印出最后一行完成! data printed to file kq.txt but it doesn't really do. 数据打印到文件kq.txt中,但实际上并没有。 If i remove the kq.txt file, it works well. 如果我删除kq.txt文件,则效果很好。 And if I change a little in kq.txt (change a number), it work well too. 而且,如果我在kq.txt中进行了一些更改(更改了一个数字),它也可以正常工作。

Can anyone explain why ? 谁能解释为什么? Thanks 谢谢

I solved my problem! 我解决了我的问题!

Because I use relative path with filename, so when I run: 因为我使用带有文件名的相对路径,所以当我运行时:

famihug@hvn:/home/famihug%~/bin/leecher.py; cat ~/bin/kq.txt                [0]

it created a new kq.txt in /home/famihug/ , not in /home/famihug/bin/ That why I keep getting old result when cat ~/bin/kq.txt 它在/ home / famihug /中创建了一个新的kq.txt ,而不是在/ home / famihug / bin /中创建了这个为什么我在cat〜/ bin / kq.txt时仍然会得到旧结果

Solution to this is: use a absolute path instead of relative path: 解决方案是:使用绝对路径而不是相对路径:

def fix_path(filename):
    filepath = os.path.realpath(__file__)
    path = os.path.dirname(filepath)
    fixed = os.path.join(path, filename)
    return fixed

fw = codecs.open(fix_path(FILE_NAME), 'w', 'utf-8')

I have no clue, but try chmod 755 script_name This is probably due to not having permissions to overright file. 我不知道,但是尝试使用chmod 755 script_name可能是由于没有权限覆盖文件。 But really, I have no clue, and I can't test it because I'm not on my computer, I'm using a friends computer. 但实际上,我没有任何线索,我无法测试它,因为我不在电脑上,而是在使用朋友电脑。 Will get back to question when I get my computer back. 当我拿回计算机时,我将再次提问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这个python脚本不起作用? - why does this python script not work? 为什么`script.py &lt;(cat * .gz)`在python 2中与subprocess.Popen一起使用,但在python 3中却不起作用? - Why does `script.py <(cat *.gz)` work with subprocess.Popen in python 2 but not python 3? 为什么在__name__ ==“ __main__”下使用manage.py执行脚本时会运行两次 - Why does manage.py execution script run twice when using it under if __name__ == “__main__” 为什么这个脚本不适用于线程化python - why does this script not work with threading python 为什么我的Python脚本会永远运行? - Why does my Python script run forever? 为什么deleteUI在使用此脚本的Maya Python中不起作用? - Why does deleteUI not work in Maya Python with this script? 为什么Python脚本适用于Windows而不适用于Linux? - Why does a Python script work on Windows and not in Linux? Crontab无法运行我的python脚本usi.py - Crontab does not run my python script usi.py 为什么这在Python IDLE shell中有效,但在我从命令提示符下作为Python脚本运行时却没有? - Why does this work in the Python IDLE shell but not when I run it as a Python script from the command prompt? 为什么Transcrypt编译在以下行的Python脚本中不起作用:os.system(&#39;python -m transcrypt -b -m -n <somePythonFile> .py&#39;)? - Why does Transcrypt compilation not work inside a Python script with the line: os.system('python -m transcrypt -b -m -n <somePythonFile>.py')?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM