I put this in a comment, but I will reply in response to be a little more thorough. It is not clear if you want to run HelloWorld.py as a script, or if you want to import something inside it. However, these are two different things.
If you just want to run HelloWorld.py from cmd or Powershell, you will need to change the PATH environment variable. On Windows, you do this in My Computer> Properties> Advanced> Environment Variables. Press PATH and add the path to the folder containing HelloWorld.py and save the changes. You will need to restart cmd or Powershell to see the changes and the changes will be saved. (This is a constant change in other words)
If you want to import the contents of HelloWorld, you have several options, but the simplest would be to turn the code you want to import into the HelloWorld.py function. So say your current HelloWorld.py looks like this:
print "Hello World!"
Change it like this:
def hello_world(): print "Hello World!"
Then you just need to add the path to the folder containing HelloWorld.py in sys.path. Looks like you already did it. So, you can import like this:
import HelloWorld HelloWorld.hello_world()
If you still want HelloWorld.py to act like a script, you need to add this to the bottom of your script:
if __name__ == 'main': hello_world()
This tells Python to import the file without starting it if it is imported. If it is not imported, it will execute the code in the if block.
Hope this clears it. This is definitely a common source of confusion for people starting out with Python.
user2233949
source share