Python:具有不同工作目录的子进程

发布于 2024-09-24 01:20:25 字数 554 浏览 0 评论 0原文

我有一个位于此目录下的 python 脚本:

work/project/test/a.py

a.py 内,我使用 subprocess.POPEN 从另一个目录启动进程,

work/to_launch/file1.pl, file2.py, file3.py, ...

Python 代码:

subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl") 

在 work/ 下project/ 时,我输入以下

[user@machine project]python test/a.py,

错误“file2.py,'没有这样的文件或目录'”

如何添加 work/to_launch/,以便这些依赖文件 file2.py 可以找到吗?

I have a python script that is under this directory:

work/project/test/a.py

Inside a.py, I use subprocess.POPEN to launch the process from another directory,

work/to_launch/file1.pl, file2.py, file3.py, ...

Python Code:

subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl") 

and under work/project/, I type the following

[user@machine project]python test/a.py,

error "file2.py, 'No such file or directory'"

How can I add work/to_launch/, so that these dependent files file2.py can be found?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幸福不弃 2024-10-01 01:20:25

您的代码不起作用,因为相对路径是相对于您当前位置的(test/a.py 上一级)。

sys.path[0] 中,您拥有当前运行脚本的路径。

将 os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) 与 relPathToLaunch = '../to_launch/file1.pl' 结合使用获取 file1.pl 的绝对路径并使用它运行 perl

编辑:如果您想从其目录启动 file1.pl 然后返回,只需记住您当前的工作目录,然后切换回来:

origWD = os.getcwd() # remember our original working directory

os.chdir(os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch))
subprocess.POPEN("usr/bin/perl ./file1.pl") 
[...]

os.chdir(origWD) # get back to our original working directory

Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py).

In sys.path[0] you have the path of your currently running script.

Use os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) with relPathToLaunch = '../to_launch/file1.pl' to get the absolute path to your file1.pl and run perl with it.

EDIT: if you want to launch file1.pl from its directory and then return back, just remember your current working directory and then switch back:

origWD = os.getcwd() # remember our original working directory

os.chdir(os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch))
subprocess.POPEN("usr/bin/perl ./file1.pl") 
[...]

os.chdir(origWD) # get back to our original working directory
帅的被狗咬 2024-10-01 01:20:25

使用相对于脚本的路径,而不是当前工作目录

os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)

另请参阅我对 Python:获取姐妹目录中文件的路径?

Use paths relative to the script, not the current working directory

os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)

See also my answer to Python: get path to file in sister directory?

凝望流年 2024-10-01 01:20:25

您可以使用此代码来设置当前目录:

import os
os.chdir("/path/to/your/files")

You could use this code to set the current directory:

import os
os.chdir("/path/to/your/files")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文