Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Subprocess lib
#1
Hello guys,

I've been experimenting with the subprocess library in python 3.5 on linux.

I've been able to run a few commands with success, but when it comes to run more than one commands at a time, I
don't seem to able to do it. Take a look at this code :
import subprocess, shlex 

command1 = 'ls -laZ > file1.txt'  
args = shlex.split(command1)
#print (args)
final = subprocess.Popen(args)
I can run the command ls with its arguments fine, but when I want to redirect the output with > to a a new file (file1) I get the following errors :

Error:
['ls', '-laZ', '>', 'file1.txt'] ls: cannot access '>': No such file or directory ls: cannot access 'file1.txt': No such file or directory
I've already tried to use shell=True, but it has no affect. In conclusion is there a way to run several commands at once with subprocess lib instead of just one (with or not its arguments) ?

Thank you for reading this.
Reply
#2
remove the split
import subprocess
 
command1 = 'ls -laZ > file1.txt'  
final = subprocess.Popen(command1, shell=True)
Or you could just pipe it through python
import subprocess
 
command1 = 'ls -laZ'  
proc = subprocess.Popen(command1.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
with open('file1.txt','w') as f:
    f.write('{}{}'.format(out, err))
Recommended Tutorials:
Reply
#3
It worked fine without the slip. Bit since the shell is True, my program is vulnerable to shell injection which I did not want to, I must read the documentation better, because I saw if the command was a string, like I have now, shell injection won't work. Do you know perhaps something more about this ?

Thank you so much for your answer, really helped me out.   Dance
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020