Problem Returning sh: 0: -c requires an argument

Asked

Viewed 55 times

2

Good guys next, 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 there terminal type ls -la it return me 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 into the terminal as ls-la. If I type ls, pwd, id and etc unique commands right, it returns me the result in a good. Problem goes to compound command. Searching the internet I realized that it is something direct from the linux shell, it is not an error but a return in which he can not identify.

I would like the help of vcs or is has some other way to effect the process with compound commands thanks.

1 answer

2


You are iterating over the command line arguments, so each of them will be run 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 argument (see in your output that it shows only the names of the files, in one line) and the second is that is causing this strange error (which I do not know what it means, because I do not have much familiarity with os.system).

I think what you want is to take the arguments of the second forward and recombine them in 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                
  • Thank you @mgibsonbr solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.