2016-07-05 32 views
0

我太新的Python IM试图通过变量与Wget的与wget的蟒通变量和检查结果

代码:

USERID = 201   
RES = os.system("wget http://localhost/ -O /usr/setting.txt") 
if RES == error: 
print RES 
else 
print 'good' 

什么,我需要传递是

http://localhost/?userid=203 or username=james 

和然后读取收到的数据

我该如何做到这一点?

相信我我看了很多贴的东西,但我仍然迷失。

谢谢:)

+1

为什么不使用'urllib2.urlopen()'或'requests'模块来检索URL?你需要将响应存储在文件中吗? – mhawke

+0

@mhawke我被要求使用** os.system **,是的,我需要将设置保存到文件 – Jah

回答

1

既然你必须使用os.system()可以构造命令字符串像这样有些奇怪约束:

import os 

user_id = 201  
dest_filename = '/tmp/setting.txt' 
command = 'wget http://localhost/userid={} -O {}'.format(user_id, dest_filename) 
res = os.system(command) 
if res == 0: 
    with open(dest_filename) as f: 
     response = f.read() 
     # process response 
else: 
    print('Command {!r} failed with exit code {}'.format(command, rv)) 

您可以调整命令结构使用的用户名:

user_name = 'james' 
command = 'wget http://localhost/username={} -O {}'.format(user_name, dest_filename) 
+0

这不是我的选择:(我必须使用它。 – Jah

+0

我怎样才能一次使用多个变量?例如:userid = 10&cmd = list我试过**命令='wget http:// localhost/username = {}&cmd = {} -O {}'。format(cmd,cmd,dest_filename)**但它不工作 – Jah

+1

这将只添加'cmd'两次。执行此操作:'command ='wget http:// localhost/userid = {}&cmd = {}'.format(user_id,cmd,dest_filename)' – mhawke