问题:...它改变一些变量,如URL和文件FILE1.TXT位置
目前还不清楚你想要chk_data
做什么。 尝试了您的示例代码,发现您正在阅读chk_data
,但之后无所作为。请编辑您的问题,并使用示例数据对此进行更详细的解释。
该实施例可以用不同的url
,file lcation
和filename
使用。
注意:我用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 module
和import 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
调用'test.py'与参数。例如。 'python test.py。其次将'test.py'作为'module'和'import'放到更高级别的脚本中。 –
stovfl
谢谢,我需要提供文件名的完整路径作为参数吗? – Rebbeca
一般来说,是取决于你从哪个文件夹调用脚本。您的示例代码保存到当前文件夹中。 – stovfl