Using subprocess with fab in python
I am new to Python and am trying to use a subprocess to run a script inside another script. I found several resources on the internet that were very close, but unfortunately did not help me run my code without errors.
Here's what I want to do: In my script1 (main script) I create a file fabfile.py (script2). This script2 or fabfile.py must be executed from script1. After some research I realized that execfile and os.systems are not good options, so I decided to use subprocess. (Ref: How can I make one python file another? )
Here's what I am doing but not working:
from os.path import expanduser
home = expanduser("~")
import os
os.getcwd()
desk = "/Desktop"
path = str(home)+str(desk)
f = open("fabfile.py","w") # Creating a fabfile.py
f.write("from fabric.api import run \ndef task1(): \n run('ls')")
import subprocess
host = raw_input("Enter the host IP with username e.g. root@10.0.0.2:")
p1 = subprocess.Popen(['fab', '-f path/fabfile.py', '-H host'],stdout=subprocess.PIPE)
output = p1.communicate()
print output
Note. In line
p1 = subprocess.Popen(['fab', '-f path/fabfile.py', '-H host'],stdout=subprocess.PIPE)
I've tried MANY different formats - placing quotes and double quotes, $
and %
for a variable, etc. and so on, but none of them work. Any idea what I am doing wrong? The examples I see are usually straightforward, without using variables as arguments.
source to share
- Don't put python variables in line
-
Individual flags
p1 = subprocess.Popen(['fab', '-f', path+'/fabfile.py', '-H', host],stdout=subprocess.PIPE)
-
When joining paths, it is better to use os.path.join ()
fab_file = os.path.join(os.path.expanduser("~"), "Desktop", 'fabfile.py')
source to share
I realized that there is another problem, that is, entering the password. Because even after fixing the problem with the variable, I get the error (different). I think, instead of using fab, I can just do,
from subprocess import Popen, PIPE
host = raw_input("Enter the host IP with user e.g. root@10.0.0.2:")
conn1 = Popen(['ssh',host,'ls'], stdin=PIPE)
conn1.communicate('password')
Reference: Use subprocess to send password
source to share
Python won't interpolate variables path
and host
for you, you need to do it explicitly.
Edit:
p1 = subprocess.Popen(['fab', '-f path/fabfile.py', '-H host'],stdout=subprocess.PIPE)
in
p1 = subprocess.Popen(['fab', '-f ' + path + '/fabfile.py', '-H ' + host],stdout=subprocess.PIPE)
source to share