小编dbi*_*hop的帖子

在另一个目录中打开文件(Python)

我一直对Python中的目录遍历问题感到困惑,并且有一种我很好奇的情况:我有一个文件,我想在一个与我当前所在的目录基本平行的目录中访问.鉴于此目录结构:

\parentDirectory
    \subfldr1
        -testfile.txt
    \subfldr2
        -fileOpener.py
Run Code Online (Sandbox Code Playgroud)

我试图在fileOpener.py中编写脚本以退出subfldr2,进入subfldr1,然后在testfile.txt上调用open().

从浏览stackoverflow,我看到人们使用osos.path完成此操作,但我只找到了关于脚本源下的子目录中的文件的示例.

在这方面,我意识到我可以将脚本重新定位到subfldr1然后一切都会很好,但我的好奇心是如何实现这一点.

编辑:这个问题特别适用于Windows机器,因为我不知道驱动器字母和反斜杠将如何影响到这一点.

python windows os.path

13
推荐指数
4
解决办法
7万
查看次数

在后台执行子进程

我有一个python脚本,它接受一个输入,将其格式化为一个命令,调用服务器上的另一个脚本,然后使用子进程执行:

import sys, subprocess

thingy = sys.argv[1]

command = 'usr/local/bin/otherscript.pl {0} &'.format(thingy)
command_list = command.split()
subprocess.call(command_list)
Run Code Online (Sandbox Code Playgroud)

我追加&到最后因为otherscript.pl需要一些时间来执行,我更喜欢在后台运行.但是,脚本似乎仍然执行而没有让我重新控制shell,我必须等到执行完成后才能回到我的提示符.有没有其他方法可以subprocess在后台完全运行脚本?

python bash subprocess

10
推荐指数
2
解决办法
2万
查看次数

Python 线程/守护进程

自学编程的学生,所以我对所有业余错误表示歉意。我想学习一些更深层次的主题,所以我试图了解线程和异常处理。

import threading
import sys
from time import sleep
from random import randint as r

def waiter(n):
    print "Starting thread " + str(n)
    wait_time = r(1,10)
    sleep(wait_time)
    print "Exiting thread " + str(n)

if __name__=='__main__':
    try:
        for i in range(5):
            t = threading.Thread(target=waiter, args=(i+1,))
            t.daemon = True
            t.start()
            sleep(3)
        print 'All threads complete!'
        sys.exit(1)
    except KeyboardInterrupt:
        print ''
        sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

该脚本只是在随机时间后启动和停止线程,如果收到^C. 我注意到当某些线程完成时它不会打印:

Starting thread 1
Starting thread 2
Starting thread 3
Exiting thread 3
Exiting thread 2
Starting thread …
Run Code Online (Sandbox Code Playgroud)

python multithreading daemon

4
推荐指数
1
解决办法
3724
查看次数

标签 统计

python ×3

bash ×1

daemon ×1

multithreading ×1

os.path ×1

subprocess ×1

windows ×1