简体   繁体   English

如何在命令行中运行 python 脚本

[英]How to run python script in command line

I want to run a python script which is located in "path=/home/user/code" in another python code by os.system, in linux.我想运行一个 python 脚本,该脚本位于另一个 python 代码中的“path=/home/user/code”,在 linux 中。 I run the following code and it runs well:我运行以下代码,它运行良好:

os.system("cd "+path+ ";" + "./update.py")

But I want to run the script without changing the current directory.但我想在不更改当前目录的情况下运行脚本。 So when I run the following code:因此,当我运行以下代码时:

os.system("."+path + "/update.py")

I get an error that says: "./home/user/code/update.py not found"我收到一条错误消息:“./home/user/code/update.py not found”

How can I solve it?我该如何解决?

remove the "."去除 ”。” at the start of the command.在命令的开头。 By typing "./home/..." your are asking to python to search for a folder called "home" in the current directory.通过键入“./home/...”,您要求 python 在当前目录中搜索名为“home”的文件夹。 If you remove the ".", the path will be interpreted as absolute and it should work.如果删除“.”,则路径将被解释为绝对路径并且它应该可以工作。 You also might have to start the command by "python".您可能还必须通过“python”启动命令。 So your final command will be所以你的最终命令将是
python /home/user/code/update.py

to correct it:纠正它:

os.system(path + "/update.py")

so basically it will be like - os.system(/home/user/code/update.py)所以基本上它会像 - os.system(/home/user/code/update.py)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM