如何在 Google Colab 笔记本中的“.py”文件中运行 Python 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51194303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a Python script in a '.py' file from a Google Colab notebook?
提问by user2458922
%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
%run rl_base.py
I run this giving error saying rl_base.py file not found. I have uploaded the same to gdrive in colab and from the same folder I am running my .ipynb file, containing the above code
我运行此错误提示未找到 rl_base.py 文件。我已将相同的内容上传到 colab 中的 gdrive 并从运行我的 .ipynb 文件的同一文件夹中,其中包含上述代码
回答by Ganesh M S
If you have the test.py file in the corresponding folder in drive as in the below attached image, then the command which you use to run the test.py file is as mentioned below,
如果您在驱动器中的相应文件夹中有 test.py 文件,如下图所示,那么您用来运行 test.py 文件的命令如下所述,
!python gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/test.py
Additional Info:
附加信息:
If you jusst want to run !python test.py
then you should change directory, by the following command before it,
如果你只是想运行,!python test.py
那么你应该改变目录,在它之前通过以下命令,
%cd gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/
回答by Bernard Swart
When you run your notebook from Google drive, an instance is created only for the notebook. To make the other files in your Google drive folder available you can mount your Google drive with:
当您从 Google Drive 运行您的笔记本时,只会为该笔记本创建一个实例。要使 Google 驱动器文件夹中的其他文件可用,您可以使用以下命令安装 Google 驱动器:
from google.colab import drive
drive.mount('/content/gdrive')
Then copy the file you need into the instance with:
然后将您需要的文件复制到实例中:
!cp gdrive/My\ Drive/path/to/my/file.py .
And run your script:
并运行您的脚本:
!python file.py
回答by korakot
You should not upload to gdrive. You should upload it to Colab instead, by calling
您不应该上传到 gdrive。您应该通过调用将其上传到 Colab
from google.colab import files
files.upload()
回答by Samruddhi Chitnis
1. Check in which directory you are using the command
1.查看你在哪个目录下使用命令
!ls
!ls
2.Navigate to the directory where your python script(file.py) is located using the command
2.使用命令导航到你的python脚本(file.py)所在的目录
%cd path/to/the/python/file
%cd path/to/the/python/file
3.Run the python script by using the command
3.使用命令运行python脚本
!python file.py
!python 文件.py
回答by Hu Xixi
It seems necessary to put the .py file's name in ""!python "file.py"
似乎有必要将 .py 文件的名称放在“”中!python "file.py"