Python: Referencing another project

2019-01-25 20:42发布

I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders.

One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want into a single directory and then run Python. Is there a better method of doing this?

Note: I am actually programming in Eclipse, but I want to be able to run the program remotely.

Similar questions:

5条回答
我想做一个坏孩纸
2楼-- · 2019-01-25 21:12

First, I make sure that the module I want to include hasn't been installed globally. Then I add a symlink within the includee's directory:

# With pwd == module to which I want to add functionality.
ln -s /path/to/some_other_module_to_include .

and then I can do a standard import. This allows multiple versions etc. It does not require changing any global settings, and you don't need to change the program code if you work on different machines (just change the symlink).

查看更多
祖国的老花朵
3楼-- · 2019-01-25 21:17

If by "run modules" you mean importing them, you might be interested in this question I asked a while ago.

查看更多
Lonely孤独者°
4楼-- · 2019-01-25 21:28

If you import sys, it contains a list of the directories in PYTHONPATH as sys.path

Adding directories to this list (sys.path.append("my/path")) allows you to import from those locations in the current module as normal without changing the global settings on your system.

查看更多
爷、活的狠高调
5楼-- · 2019-01-25 21:28

Take a look at tools like

  1. virtualenv, to set up a virtual python, in which you can install your modules without getting them globally. http://pypi.python.org/pypi/virtualenv

  2. Setuptools, which allows you to specify (and automatically install) dependencies for your modules. http://pypi.python.org/pypi/setuptools (If you have problems with setuptools, take a look at Distribute, a maintained fork. http://pypi.python.org/pypi/distribute )

  3. Buildout, which allows you deploy a complete application environment, including third-party software such as MySQL or anything else. http://pypi.python.org/pypi/zc.buildout/

查看更多
地球回转人心会变
6楼-- · 2019-01-25 21:30

I just realised that I have actually solved this problem before. Here is the approach I used - much more complex than mavnn, but I was also solving the problem of running a Python2.x program from a Python 3.0

import os
import subprocess
env=os.environ.copy()
env['PYTHONPATH']=my_libraries
kwargs={"stdin":subprocess.PIPE, "env":env}
subprocess.Popen(["python","-u",program_path],**kwargs)
查看更多
登录 后发表回答