Search code examples
pythonsubprocesspopen

For loop with sub-process not working


with open('Client.txt','r') as Client_Name: 
   for Client in Client_Name.readlines(): 
       f=file('data_output','w') 
       p1 = subprocess.Popen(['nbcommand', '-byclient', Client], stdout=f, stderr=subprocess.PIPE)
       p1.wait() 
       f.close()

When I use the subprocess with for loop. The output is empty. But if I just #put a client name and run the script the output is fine. How do I loop it for different clients . Any Suggestion ??? Thanks,

Client = 'abcd'  
f=file('data_output','w')  
p1 = subprocess.Popen(['nbcommand', '-byclient', Client], stdout=f,stderr=subprocess.PIPE)
p1.wait()  
f.close()

Solution

  • When you use for Client in Client_Name.readlines() you get the line with '\n' at the end. So you either rstrip() that or use Client_Name.read().splitlines() to get rid of that new line character, for example:

    with open('Client.txt','r') as Client_Name: 
        for Client in Client_Name.read().splitlines(): 
            # rest of code
    

    or:

    with open('Client.txt','r') as Client_Name: 
        for Client in Client_Name.readlines(): 
            Client = Client.rstrip()
            # rest of code