我的项目看起来像这样:
running-pycharm-project-at-cmd
- main.py
- c
- run_project.py
- z
- __init__.py
- the_module.py
- y
- __init__.py
- template.md
- the_module_module.py
- the_support_function.py
.py文件的内容如下所示:
main.py
from c.run_project import run
print('running main.py...')
run()
c/run_project.py
from c.z.the_module import the_module_function, the_module_write_function
def run():
print('Running run_project.py!')
the_module_function()
# write a file:
the_module_write_function(read_file='./z/y/template.md', write_file='../README.md')
if __name__ == '__main__':
run()
c/z/the_module.py
from c.z.y.the_module_module import the_module_module_function
def the_module_function():
print('the_module_function is running!')
the_module_module_function()
pass
def the_module_write_function(read_file, write_file):
with open(read_file, 'r') as fid:
with open(write_file, 'w') as fid_out:
contents = fid.read()
contents.replace('{}', 'THE-FINAL-PRODUCT!')
fid_out.write(contents)
c/z/y/the_module_module.py
from .the_support_function import this_support_data
def the_module_module_function():
print('The module module function is running!')
print("Here is support data: {}".format(this_support_data))
pass
c/z/y/the_support_function.py
this_support_data = "I am the support data!"
GitHub repo使复制更容易:running-pycharm-project-at-cmd
问题:在Pycharm中以 running-pycharm-project-at-cmd
为根加载项目 . 然后我右键单击并运行run_project.py文件 . 一切正常 . 我无法弄清楚如何以相同的方式从命令行运行 run_project.py
. 创建 main.py
是a workaround suggested elsewhere,但由于对模板文件的相对引用而失败(在实际项目中, y
文件夹是一个git子模块,因此不能在其中包含绝对引用) .
2 回答
我回到了这里,并且能够让它运转起来 . 请注意,我在Windows 7上,其中一些可能与平台有关 . 为了在不更改任何代码的情况下使其工作,关键是在运行之前设置PYTHONPATH环境变量 . PyCharm会自动执行此操作(默认情况下,它可在“运行配置”选项中进行配置) .
脚步:
重新创建问题:
将github repo克隆到G:\ TEST .
导航到G:\ TEST \ running-pycharm-project-at-cmd-master \ c
python run_project.py
Traceback (most recent call last): File "run_project.py", line 1, in <module> from c.z.the_module import the_module_function, the_module_write_function ImportError: No module named 'c'
最简单的解决方案(如果能够从脚本位置运行Python):
SET PYTHONPATH=G:\TEST\running-pycharm-project-at-cmd-master
python run_project.py
Running run_project.py! the_module_function is running! The module module function is running! Here is support data: I am the support data!
从远程位置运行(这绝对是Windows特定的):
START cmd /K "cd G:\TEST\running-pycharm-project-at-cmd-master\c & python run_project.py"
G:\TEST\myotherlocation run_it.bat
Running run_project.py! the_module_function is running! The module module function is running! Here is support data: I am the support data!
如果将main.py文件复制到
c
文件夹并将其重命名为__init__.py
,则可以运行:$ python -m c
-m
参数告诉python运行模块或包(在本例中为c
) . Python将在c
的文件夹中查找__init__.py
文件并运行它 . 您只需要确保文件夹c位于PYTHONPATH中,或者是当前工作目录的子文件夹 .