Herbert
Herbert

Reputation: 21

access to file-output of external program

I'm trying to call a program from within Python that creates output and I want to work with this output when the external program has finished. The programstring is

"sudo fing -r 1 > fingoutput.txt".

I managed to call the program with

from subprocess import call

cmd = ['sudo', 'fing', '-r 1']

call(cmd)

but I can't direct it's output to a file.

cmd = ['sudo', 'fing', '-r 1 > fingoutput.txt']

or

cmd = ['sudo', 'fing', '-r 1', '> fingoutput.txt']

produce

Error: multiple occurrences

I want to write the output to a file because it might be thousands of lines.

Thank you for your help,

Herbert.

Upvotes: 2

Views: 83

Answers (2)

Adarsh Dinesh
Adarsh Dinesh

Reputation: 106

If you want to redirect to file from the shell-script itself you can always go for this

cmd = 'sudo fing -r 1 > fingoutput.txt'
call(cmd, shell=True)

Or

cmd = 'sudo fing -r 1 > fingoutput.txt'
p = Popen(cmd, shell=True, stdout=PIPE, stdin=PIPE)

Keeping shell=True may lead to security issues.

Upvotes: 0

Leistungsabfall
Leistungsabfall

Reputation: 6488

You can use the stdout argument to redirect the output of your command to a file:

from subprocess import call

cmd = ['sudo', 'fing', '-r 1']
file_ = open('your_file.txt', 'w')  
call(cmd, stdout=file_)

Upvotes: 1

Related Questions