0

I'm trying to make a simple if-check in python. I check for a certain hostname and set path accordingly.

But the result is unexplainable to me.

hostname = os.system('hostname')

if(hostname == 'rkim'):
    path = '/home/forge/rkim-web-app/'
    # This block of code should be running 
else:
    path = '/Applications/MAMP/htdocs/code/rkim-web-app/'
    # But this block of code run instead

Result :

python /home/forge/rkim-web-app/database/backup_mysql.py

rkim <-------- hostname printed == rkim 

Traceback (most recent call last):
  File "/home/forge/rkim-web-app/database/backup_mysql.py", line 28, in <module>
    file = open(path + '.env', "r")
IOError: [Errno 2] No such file or directory: '/Applications/MAMP/htdocs/code/rkim-web-app/.env'

What did I do wrong ?

6
  • 1
    From os.system's documentation: "the return value is the exit status of the process" Commented Mar 6, 2017 at 18:59
  • hostname isn't what you think it is Commented Mar 6, 2017 at 18:59
  • @Cfreak : Why is it print like that ? Commented Mar 6, 2017 at 19:00
  • @spectras : what is the possible alternative then ? Any suggestions ? Commented Mar 6, 2017 at 19:00
  • /Applications/MAMP/htdocs/code/rkim-web-app/.env exist on my Mac OS X. Commented Mar 6, 2017 at 19:12

1 Answer 1

3

os.system('command') seems to return exit status but prints the hostname. Instead of os module, use platform module to get the host name.

import platform 
hostname = platform.node()

if(hostname == 'rkim'):
    path = '/home/forge/rkim-web-app/'
else:
    path = '/Applications/MAMP/htdocs/code/rkim-web-app/'
Sign up to request clarification or add additional context in comments.

4 Comments

Will I need to install any extra module on my linux machine or Mac OS to use this code ??
Also, do you mean host = platform.node() ? or hostname = platform.node() ?
Thanks. Just checking. :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.