How to run shell commands from python.
eg. How to use 'echo $a' commands? where a is any variable.

Recommended Answers

All 5 Replies

Try this:

import os

a = 'hello'
cmd_string = "echo $%s" % a
os.system(cmd_string)

hi,

It was returning the return code(0). How to get the output as 'hello'?

I think Z is applying this to a Windows batch command.

hi,

It was returning the return code(0). How to get the output as 'hello'?

The return value is 0 because the command you gave, actually executed successfully. os.sytem("echo hello"); os.system("ren file-old file-new") If you want to print something on the screen, there is already print function available in Python.

If you are trying to execute any command and want to get its output, you can redirect command output to a file. os.system("dir > output") kath.

cmd_string = 'echo ' + a
os.system(cmd_string)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.