How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

后端 未结 5 1342
后悔当初
后悔当初 2020-11-22 11:20

How can I make any use of PYTHONPATH? When I try to run a script in the path the file is not found. When I cd to the directory holding the script the script runs. So what go

5条回答
  •  萌比男神i
    2020-11-22 11:53

    I think you're mixed up between PATH and PYTHONPATH. All you have to do to run a 'script' is have it's parental directory appended to your PATH variable. You can test this by running

    which myscript.py
    

    Also, if myscripy.py depends on custom modules, their parental directories must also be added to the PYTHONPATH variable. Unfortunately, because the designers of python were clearly on drugs, testing your imports in the repl with the following will not guarantee that your PYTHONPATH is set properly for use in a script. This part of python programming is magic and can't be answered appropriately on stackoverflow.

    $python
    Python 2.7.8 blahblahblah
    ...
    >from mymodule.submodule import ClassName
    >test = ClassName()
    >^D
    $myscript_that_needs_mymodule.submodule.py
    Traceback (most recent call last):
      File "myscript_that_needs_mymodule.submodule.py", line 5, in 
        from mymodule.submodule import ClassName
      File "/path/to/myscript_that_needs_mymodule.submodule.py", line 5, in 
        from mymodule.submodule import ClassName
    ImportError: No module named submodule
    

提交回复
热议问题