I am newbie to python, and for GUIs, I use wxpython.
My Issue is this:
I have to create a debian file for two types of products(say product 1 and product 2).That can be done by running README.package.creation file. For "product1" in ".bashrc" we have to change
Product = product1
After that we have to do "make clean" in new terminal(otherwise changes in .bashrc will not take effect i.e "product" may not be equal to "product 1" if we dont follow the procedure), then we have to run ./Readme.package.creation.process. In Readme.package.creation then it takes automatically product type as "product 1"
If I does this manually it will work fine but if i do this through GUI it Readme.package.creation file will not take product type. From python null value will be sent.
Please help to solve my issue.
My code is:
subprocess.call("sed -i '/export PRODUCT/d' .bashrc", shell=True)
subprocess.call("sed -i '/export BOARD=TYpe/ a\ export PRODUCT=product1' .bashrc", shell=True)
os.chdir("/home/x/y/z")
subprocess.call("make clean", shell=True)
os.chdir("/home/x/main/src/package")
subprocess.call("sed -i 's/re.build -f -gui -p all/re.build -gui -p all -svn no/' README.package.creation", shell=True)
subprocess.call("gksu debian", shell=True)
subprocess.Popen("xfce4-terminal -e 'bash -c \"./README.package.creation -u %s\";sleep 10'" % (str(u_name)),shell=True)
How to do after that I have to follow same procedure for Product 2 also
EDIT:
How about os.environ in python?
I have tried to change with os.putenv and then os.environ seems like it doesnot work fine.
Try:
import OS
os.environ['product']='product1'
subprocess.call("make clean", shell=True)
and so on
Your problem is very simple, and so is the solution:.
In the subprocess.Popen(...), change the call from:
subprocess.Popen("xfce4-terminal -e 'bash -c \"./README.package.creation -u %s\";sleep 10'" % (str(u_name)),shell=True)
to:
subprocess.Popen("xfce4-terminal -e 'bash -c \"source ~/.bashrc; ./README.package.creation -u %s\";sleep 10'" % (str(u_name)),shell=True)
Essentially, you're asking bash to source the .bashrc file before calling the package creation command.
Another illustration:
sgulati#precise:~$ cat /tmp/1.sh
export A=100
sgulati#precise:~$ python -c "import subprocess
print subprocess.Popen(['bash', '-c', 'source /tmp/1.sh; echo \$A'], stdout=subprocess.PIPE).stdout.read()"
100
In this example, I declare the variable A=100 in /tmp/1.sh, source it and then execute echo $A. Because of source /tmp/1.sh, the value of A is known when echo $A is executed.
Please note that the syntax I used in my example is the syntax from python 2.7.3, but the concept is pretty much identical, no matter how you go about it.
Related
I am trying to run a C executable say c4.5 and c4.5rules which will take a single command line argument inside a python code using os.system, I am using the C executable written by some other person, and I don't have the original .c file with me. I need to write like below to make sure that executable file is doing okay.
import sys
import os
dataset = sys.argv[1]
os.system(f"/home/Dev/c4.5 -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset}")
os.system(f"/home/Dev/c4.5rules -u -f {dataset} > Temp")
f = open('Temp')
...
And if I remove that -u and -f, then it is not working.
Why is it happening and what is the use of -u and -f?
The following command opens a new shell and opens nano in it, when I type it into bash:
gnome-terminal -e "bash -c 'nano test; bash'"
So I tried the same in my python code with subprocess:
import subprocess
command = "gnome-terminal"
args = " -e \"bash -c 'nano test; bash'\""
subprocess.call([command, args])
I have tried already many combinations. Basically I just want to open a shell with a specific file in nano.
First I thought this would be one the easiest steps, but it turned out to be very difficult. Don't know if the problem exists due to the masking or if it's a common problem with passing variables like I am used to in shells. So it might be rather a question for AskUbuntu or the Unix section ... not sure ...
The args should be the same set of individual strings you use on the command line. It's easier to think about if you construct the list all at once. gnome-terminal is the command, and it takes two arguments. (The second argument is more commonly thought of as the argument to the -e option, but from the caller's perspective, it's just two arguments. gnome-terminal itself is the one that groups them together as an option/argument pair.)
command = ["gnome-terminal", "-e", "bash -c 'nano test; bash'"]
subprocess.call(command)
(Note that you could just pass a single string and let the shell sort it out, but the explicit argument list is superior.
subprocess.call('''gnome-terminal -e "bash -c 'nano test; bash'"''', shell=True)
)
From Python:
output = os.popen("ps -o cmd=1").read()
print output
Output:
1
/bin/bash
python myPython.pyc
sh -c ps -o cmd=1
ps -o cmd=1
But when I run that command from terminal it returns what I want:
/sbin/init
Also, when I run "ls -l" command from python, it returns correct thing.
My main purpose is finding name of process from its PID in Python.
What should I do ?
This does not answer the question regarding why you get different output, but a better approach to solving the goal you are after is to either:
Open and read /proc/<pid>/cmdline, or
Read the symbolic link /proc/<pid>/exe
EDIT: Get rid of the popen call there and the subsequent "useless use of cat". Do this instead:
with open("/proc/"+data.get("pid")+"/cmdline") as cmd:
cmdinfo=cmd.read()
command=cmdinfo.split("\0")
print command[0]
I know you have an answer now, but the reason that your original attempt did not work is probably because popen creates a brand new process, and therefore a different process environment.
When I run 'ps -o cmd=1' from my Terminal, I get similar results as you did when you used popen.
1
bash
ps -o cmd=1
I've tried what's told in How to force /bin/bash interpreter for oneliners
By doing
os.system('GREPDB="my command"')
os.system('/bin/bash -c \'$GREPDB\'')
However no luck, unfortunately I need to run this command with bash and subp isn't an option in this environment, I'm limited to python 2.4. Any suggestions to get me in the right direction?
Both commands are executed in different subshells.
Setting variables in the first system call does not affect the second system call.
You need to put two command in one string (combining them with ;).
>>> import os
>>> os.system('GREPDB="echo 123"; /bin/bash -c "$GREPDB"')
123
0
NOTE You need to use "$GREPDB" instead of '$GREPDBS'. Otherwise it is interpreted literally instead of being expanded.
If you can use subprocess:
>>> import subprocess
>>> subprocess.call('/bin/bash -c "$GREPDB"', shell=True,
... env={'GREPDB': 'echo 123'})
123
0
The solution below still initially invokes a shell, but it switches to bash for the command you are trying to execute:
os.system('/bin/bash -c "echo hello world"')
I use this:
subprocess.call(["bash","-c",cmd])
//OK, ignore this because I have not notice subprocess not considered.
subprocess.Popen(cmd, shell=True, executable='/bin/bash')
I searched this command for some days and found really working code:
import subprocess
def bash_command(cmd):
subprocess.Popen(['/bin/bash', '-c', cmd])
code="abcde"
// you can use echo options such as -e
bash_command('echo -ne "'+code+'"')
Output:
abcde
I want to run a command like this
grep -w 1 pattern <(tail -f mylogfile.log)
basically from a python script i want to monitor a log file for a specific string and continue with the python script as soon as i found that.
I am using os.system(), but that is hanging. The same command in bash works good.
I have a very old version of python (v2.3) and so don't have sub-process module.
do we have a way to acheive this
In Python 2.3, you need to use subprocess from SVN
import subprocess
import shlex
subprocess.call(shlex.split("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'"))
To be explicit, you need to install it from the SVN link above.
You need to call this with /bin/bash -c due to the shell redirection you're using
EDIT
If you want to solve this with os.system(), just wrap the command in /bin/bash -c since you're using shell redirection...
os.system("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'")
First of all, the command i think you should be using is grep -w -m 1 'pattern' <(tail -f in)
For executing commands in python, use the Popen constructor from the subprocess module. Read more at
http://docs.python.org/library/subprocess.html
If I understand correctly, you want to send the output to python like this -
tail -f mylogfile.log | grep -w 1 pattern | python yourscript.py
i.e., read all updates to the log file, and send matching lines to your script.
To read from standard input, you can use the file-like object: sys.stdin.
So your script would look like
import sys
for line in sys.stdin.readlines():
#process each line here.