Vinay
Vinay

Reputation: 13

os.system() when used with "strings" command in Ubuntu not working

Consider this command

strings --radix=d --encoding={b,l} abc.exe >> xyz.txt

When I run this on the Ubuntu terminal it works without any problems. However when I use it through a python code:

import os
os.system("strings --radix=d --encoding={b,l} abc.exe >> xyz.txt")

Its not working. If I remove the "encoding" then it works fine in both cases. However, I need to get Unicode strings so that part is necessary. Anyone have any solutions?

Upvotes: 1

Views: 988

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You don't need shell=True, you can pass a list of args and write the stdout to a file:

from subprocess import check_call
with open('xyz.txt',"a") as out:
    check_call(['strings', '--radix=d', '--encoding={b,l}', 'abc.exe'],stdout=out)

A good explanation here of what shell=True does

Upvotes: 3

mata
mata

Reputation: 69012

ubuntu uses dash by default as /bin/sh, and bash for login shells.

So in your terminal --encoding={b,l} is propably expanded by bash to --encoding=b --encoding=l, while dash (probably called by os.system as /bin/sh) does no such expansion and it remains --encoding={b,l}

The easiest way is to explicitly expand the encoding parameter and don't leave that to the shell, then it will work with any shell.

And you should use the subprocess module instead of os.system(). Just be aware that when using the shell=True argument, it will also call the default /bin/sh, which isn't guaranteed to be bash.

Upvotes: 3

Mux
Mux

Reputation: 348

os.system is outdated, use subprocess instead. u also should use shell=True to have sh like behaviour:

import subprocess

cmd = "strings --radix=d --encoding={b,l} abc.exe >> xyz.txt"
subprocess.check_call(cmd, shell=True)

It also throws exception in case of call failure!

Upvotes: 0

Related Questions