How can I add a default path to look for python script files in?

后端 未结 4 1116
醉话见心
醉话见心 2020-12-10 13:50

I\'ve always had a bit of trouble figuring out how to get Python set up properly in Windows.

I\'ve already set up path=%path%;C:\\python27 , so I\'m able to open .py

相关标签:
4条回答
  • 2020-12-10 14:28

    That's not how running scripts works. Modify your %PATH% environment variable to contain the directory that contains the script in question, then run the script from the command prompt, not IDLE.

    0 讨论(0)
  • 2020-12-10 14:31

    Please, follow a tutorial

    sys.path.append(r'C:\Users\Jimmy\Documents\Python') 
    

    You can't randomly put \ in a string.

    When you look at the error message, notice that all of the System-supplied path elements have \\ to escape the meaning of the \.

    A tutorial will show you how to use r" strings to achieve this easily.

    0 讨论(0)
  • 2020-12-10 14:35
    import sys
    sys.path.append(YOUR_PATH)  # or .insert(0, YOUR_PATH) may give higher priority
    

    or set your $PYTHONPATH environment variable

    0 讨论(0)
  • 2020-12-10 14:46

    I put this in a comment, but I'll put in in an answer to be a little more thorough. It's not clear if you want to run HelloWorld.py as a script, or if you want to import something inside it. They are 2 separate things though.

    If you just want to run HelloWorld.py from cmd or Powershell, then you'll need to modify the PATH environment variable. In Windows, you do that in My Computer > Properties > Advanced > Environment Variables. Click PATH, and add the path to the folder containing HelloWorld.py and save your changes. You'll need to restart cmd or Powershell to see the changes, and the changes will persist. (It's a permanent change in other words)

    If you want to be able to import HelloWorld contents then you have a few options, but the easiest would be to wrap the code you want to import into a function in HelloWorld.py. So say your current HelloWorld.py looks like this:

    print "Hello World!"
    

    Change it to this:

    def hello_world():
        print "Hello World!"
    

    Then, you just need to add the path to the folder containing HelloWorld.py to sys.path. It sounds like you've already done that. So then you'll be able to import like this:

    import HelloWorld
    
    HelloWorld.hello_world()
    # Will output: "Hello World!"
    

    If you still want HelloWorld.py to be able to act like a script, then you'll want to add this to the bottom of your script:

    if __name__ == 'main':
        hello_world()
    

    That tells Python to import the file without running it if it's being imported. If it's not being imported, it will execute the code in the if block.

    Hopefully that clears it up. It's definitely a common source of confusion for people starting with Python.

    0 讨论(0)
提交回复
热议问题