![](/img/trans.png)
[英]Running Python Files from Pycharm Project Folder with Windows Command Line
[英]How do I replicate the way PyCharm is running my Python 3.4 project at the command line?
我的項目看起來像這樣:
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
是其他地方建議的解決方法 ,但由於對模板文件的相對引用而失敗(在實際項目中, y
文件夾是git子模塊,因此不能在其中包含絕對引用)。
如果將main.py文件復制到c
文件夾並將其重命名為__init__.py
,則可以運行:
$ python -mc
-m
參數告訴python運行模塊或包(在本例中為c
)。 Python將在c
的文件夾中查找__init__.py
文件並運行它。 您只需要確保文件夾c位於PYTHONPATH中,或者是當前工作目錄的子文件夾。
我繞回去了,並且能夠讓它運轉起來。 請注意,我在Windows 7上,其中一些可能與平台有關。 為了在不更改任何代碼的情況下使其工作,關鍵是在運行之前設置PYTHONPATH環境變量。 PyCharm會自動執行此操作(默認情況下,它可在“運行配置”選項中配置)。
腳步:
python run_project.py
Traceback (most recent call last): File "run_project.py", line 1, in <module> from czthe_module import the_module_function, the_module_write_function ImportError: No module named 'c'
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!
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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.