Reputation: 11
I am getting following error while running subprocess.call() function.
error: must set personality to get -x option
I have shell script test.sh as below
#!/bin/bash
$1 > $2
Below is my python code
action_path = '/home/test.sh'
val1 = 'ps -ax | grep python'
val2 = '/home/cvg/cvg.log'
retval=subprocess.call([action_path,val1,val2])
I am expecting the output of the command 'ps -ax | grep python'
should be logged to file mentioned. But I am getting the file as blank and
error as mentioned at starting. Though I am able run this command succssfully on the terminal which output list of python processes running.
I do not have any clue regarding this.
Please let me know if anybody knows about it.
Upvotes: 1
Views: 525
Reputation: 295272
As an aside -- grep
ping through ps
is bad form; in general, you shouldn't do it at all, and if you do want to do it from Python, the psutil
module will do the work for you.
The heart of this issue is BashFAQ #50. Unquoted expansions like $1
(for very good, security-related reasons) don't go through the full range of shell parsing steps -- quotes, redirections, pipes, command substitutions, and other syntactical elements are generally not recognized; only string-splitting and glob expansion take place.
Also note that all of the below requires you to fix your ps
command such that it actually works when run on your local platform -- a correction out-of-scope for a Python-focused question, particularly one not tagged with a specific operating system so we can look up its ps
command's usage.
There's no reason for an intermediate shell script at all. Have your Python code open the output file directly.
subprocess.call('ps -ax | grep python', shell=True, stdout=open('/home/cvg/cvg.log', 'w'))
...or, if you really want your output file to be opened by a shell:
subprocess.call(['ps -ax | grep python >"$1"', '_', '/home/cvg/cvg.log'], shell=True)
Note that when subprocess.call()
is passed a list, the first list element is the script to run; the second is $0
, the third is $1
, etc; hence, the _
is a placeholder for $0
, and the filename becomes $1
in the context of the script.
You can have the interpreter evaluate the redirection internally:
#!/bin/sh
eval "$1" >"$2"
or, with even more inefficiency, have it start a new shell after the redirection itself (but why not have Python do that?):
#!/bin/sh
sh -c "$1" >"$2"
Upvotes: 1
Reputation: 152
Replace ps -ax
with ps -ef
.
From $ man ps
:
To see every process on the system using standard syntax:
ps -e ps -ef ps -eF ps -ely
Upvotes: 0