subprocess.call cd not working [duplicate]

2020-04-23 03:22发布

In [3]: pwd

Out[3]: u'/Users/aarcher/Desktop/scripts'


In [5]: subprocess.call(['mkdir', '-p', os.path.expanduser('~/file/path/name')])

Out[5]: 0

I verified in another terminal that it had created /Users/aarcher/file/path/name successfully, but unable to change to that directory, even when it returns 0:

In [7]: subprocess.call(['cd', os.path.expanduser('~/file/path/name')], shell=True)

Out[7]: 0

In [8]: pwd

Out[8]: u'/Users/aarcher/Desktop/scripts'

I am in unix box

2条回答
唯我独甜
2楼-- · 2020-04-23 03:50

subprocess.call() creates a new process. The cd works in that process, but when the process exits it won't affect the current process. This is how processes are designed to work.

If you need your script to change to a different directory you can use os.chdir which will change the directory for the current process.

查看更多
Melony?
3楼-- · 2020-04-23 04:04

for this task no a good idea to use suprocess. just use python os module try this::

In [12]: import os 

In [13]: os.getcwd()
Out[13]: '/home/najeeb'

In [14]: os.chdir('/home/najeeb/Desktop/project/')

In [15]: os.getcwd()
Out[15]: '/home/najeeb/Desktop/project'

In [16]: 

if now any problem you face please let me know!

查看更多
登录 后发表回答