tamakisquare
tamakisquare

Reputation: 17077

Why different behaviors between running Python module as an executable vs. Python [filename]

So, I created a simple python module, test.py

import commands

def main():
  cmd = 'ls -l'
  (status, output) = commands.getstatusoutput(cmd)
  print status, output

if __name__ == '__main__':
  main()

When I ran it using "Python test.py", I got the result that I expected. But when I ran it as an executable (yes, it has the 'x' permission), the program didn't respond at all and I had to Ctrl+C to quit it. Why is that? Shouldn't both ways give the same result?

Upvotes: 0

Views: 281

Answers (2)

voithos
voithos

Reputation: 70602

You need the hashbang to be the first line of your script, referencing the path of the Python interpreter. Otherwise, all the OS knows is that you're trying to execute a script, and it has no idea how to go about doing that.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 361919

Add a hash-bang line to the top:

#!/usr/bin/env python

import commands
...

This tells your system what interpreter to use to execute the script. Without it it doesn't know if it's a shell script, Perl script, Python script, what.

Upvotes: 6

Related Questions