Problem returning sh: 0: -c requires an argument

2

Good luck guys, I have this code below for python 2.7:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import sys
import os

if len(sys.argv) <= 3:
    for comando in sys.argv[1:]:
        shell = os.system(comando)
        print comando

But when I go to the terminal type ls -la it will return the following:

┌─[backz]@[NoSafe]:~/hk/programacao/python/manipular_arquivos
└──> $ ./comando.py ls -la
arq.txt  comando.py  executar_comando.py  grep.py  os  sys  usando_argv.py
ls
sh: 0: -c requires an argument
-la

This is only if I type a complete command in the terminal as ls -la. If I type ls, pwd, id, and so on all commands, it returns me the result in a good one. Problem occurs for compound command. Searching for the internet I realized that it is something straight from the linux shell, it is not an error but a return in which it can not identify.

I would like the help from you or is there any other way to complete the process with compiled commands thanks.

    
asked by anonymous 25.11.2015 / 02:04

1 answer

2

You're iterating over the command line arguments, so each of them will be executed individually by os.system :

if len(sys.argv) <= 3:              # arv = ['./comando.py', 'ls', '-la']
    for comando in sys.argv[1:]:    # arv[1:] = ['ls', '-la']
        shell = os.system(comando)  # comando = 'ls' (1ª iteração)
        print comando               #         = '-la' (2ª iteração)

The first ( ls ) is not receiving any arguments (see in its output that it shows only the names of the files, in a single line) and the second is that it is causing this strange error (that I do not know what it means , since I'm not very familiar with os.system ).

I think what you want is to take the arguments from the second forward and recombine them into a string, separated by spaces (note: I have not tested).

if len(sys.argv) <= 3:               # arv = ['./comando.py', 'ls', '-la']
    comando = ' '.join(sys.argv[1:]) # arv[1:] = ['ls', '-la']
    shell = os.system(comando)       # comando = 'ls -la'
    print comando                
    
25.11.2015 / 02:39