2017-06-01 58 views
0

场景:我有一个test.py文件,它具有以下代码。接受用户变量并使用python创建template.py [2,7] [redhat 6.7]

import json 
import os 
import sys 
def check() 
    url = os.popen("curl api.openweathermap.org/data/2.5/weather?id=2172797 2>dev/null") 
    uri = json.loads(url) 
    f_check = file("/home/1/file1.txt",'r') 
    f_data = f_check.read() 
    chk_data = int(f_data) 
    f1 = open("file1.txt", "w") 
    n1 = f1.write(str(uri) + "\n") 
    f1.close() 

在上述test.py文件位于位置“/家庭/勾选”我想用这个作为可用于部署在不同的位置,其他用途的模板文件说“/家/单词“只是改变它的一些变量,如用户将提供的url和file1.txt文件的位置。 我找不到一个方便的方法来做到这一点。

任何帮助将不胜感激。

+0

调用'test.py'与参数。例如。 'python test.py 。其次将'test.py'作为'module'和'import'放到更高级别的脚本中。 – stovfl

+0

谢谢,我需要提供文件名的完整路径作为参数吗? – Rebbeca

+0

一般来说,是取决于你从哪个文件夹调用脚本。您的示例代码保存到当前文件夹中。 – stovfl

回答

0

问题:...它改变一些变量,如URL和文件FILE1.TXT位置

目前还不清楚你想要chk_data做什么。 尝试了您的示例代码,发现您正在阅读chk_data,但之后无所作为。请编辑您的问题,并使用示例数据对此进行更详细的解释。


该实施例可以用不同的urlfile lcationfilename使用。

注意:我用module urllib,而不是os.popen("curl...

首个解决方案,从终端窗口传递参数:

import urllib.request 
import urllib.parse 

def check(url, params, filename): 
    params = urllib.parse.urlencode(params) 
    url = "{}?{}".format(url, params) 

    with urllib.request.urlopen(url) as f: 
     json_response = json.loads(f.read().decode('utf-8')) 

    with open(filename, 'w') as f_out: 
     f_out.write(str(json_response)) 

if __name__ == '__main__': 
    url = sys.argv[1] 
    params = {} 
    for param in sys.argv[2].split(' '): 
     key, value = param.split('=') 
     params[key] = value 

    if url == 'openweathermap.org': 
     url = 'http://samples.openweathermap.org/data/2.5/weather' 
     params['appid'] = 'b1b15e88fa797225412429c1c50c122a1' 

    check(url, params, sys.argv[3]) 

使用

:# python openweathermap.org "id=2172797" /home/word/my_file.txt 

第二种解决方案,使用test.py作为Python moduleimport check
新Python脚本中的参数。

注意:这需要home.check.test是在你的PYTHONPATH

创建一个新的*.py文件,摹openweathermap.py

from home.check.test import check 

if __name__ == '__main__': 
    url = 'http://samples.openweathermap.org/data/2.5/weather' 
    params = {'id':'2172797', 'appid':'b1b15e88fa797225412429c1c50c122a1'} 
    check(url, params, '/home/word/my_file.txt') 

使用

:# python /home/check/openweathermap.py 

测试使用Python 3.4.2