I am wracking my brain over here trying to do a simple function with python without using shell=true and am not getting the results I need. I am using python 2.7 on Linux.
I have tried multiple methods of doing this. It works fine if I use shell=true like so:
import subprocess as s
var1 = s.call("echo $HOME", shell=True)
and
import subprocess as s
var1 = s.check_output("echo $HOME", shell=True)
both return
/home/myhost
... like it should but everything else I tried fails. In most cases it seems that it is passing my variable as a string instead of a command.
These are the results I have received with the various methods:
import subprocess as s
print var1
returns
myhost@me:~/Desktop$ python home_test.py
File "home_test.py", line 42, in <module>
main()
File "home_test.py", line 11, in main
my_test()
File "home_test.py", line 16, in check_auth
var1 = s.check_output("echo $HOME")
File "/usr/lib/python2.7/subprocess.py", line 567, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Then I tried this:
import subprocess as s
var1 = s.Popen(['echo', '$HOME'], stdout=s.PIPE)
print var1
returns
myhost@me:~/Desktop$ python home_test.py
<subprocess.Popen object at 0x7f297ebcbf90>
myhost@me:~/Desktop$echo: write error: Broken pipe
Then this:
import subprocess as s
cmd1 = '$HOME'
var1 = s.Popen(['/bin/echo', cmd1], stdout=s.PIPE)
print var1
returns
('$Home\n', None)
and this
import subprocess as s
cmd1 = 'HOME'
var1 = s.Popen(['/bin/echo', cmd1], stdout=s.PIPE)
print var1
returns
myhost@me:~/Desktop$ python home_test.py
('Home\n', None)
found some doc that said to use os... which also failed, which isn't surprising after finding out this had been deprecated in 2.6.
import os
var1 = os.popen('echo $HOME')
print var1
returns
<open file 'echo $HOME', mode 'r' at 0x7f1c6b26f6f0>
sh: echo: I/O error
Then my final attempt (actually there were more... but we will just leave it at this)
import subprocess as s
var1= s.Popen(["echo", "$HOME"], stdout=s.PIPE).communicate()[0]
print var1
returns:
myhost@me:~/Desktop$ python home_test.py
$HOME
Can someone please point me in the right direction? I have spent an entire day fiddling with this and I need help please. Thank you in advance for any help given.