2017-06-01 55 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